//项目所属区域
var areaList = {
    '10001': '武昌区',
    '10002': '汉口区',
    '10003': '汉阳区',
    '10004': '东新区',
    '10005': '沌口区',
    '10006': '东西湖区',
    '10007': '黄陂区',
    '10008': '新洲区',
    '10009': '汉南区',
    '10010': '江夏区',
    '10011': '蔡甸区'
};

// 格式化操作
function operateFormatter(value, row, index) {
    var html = '';
    var operations = {
        submit: '节点提交',
        ensure: '完工',
        reject: '驳回',
        review: '查看附件',
        upload: '上传附件'
    };
    var btnColors = {
        submit: 'label-primary',
        ensure: 'label-success',
        reject: 'label-danger',
        review: 'label-default',
        upload: "label-primary"
    };
    if (!value) {
        // 操作数组为undefined
        return '';
    }
    if (value.length <= 0) {
        // 操作数组里无操作
        return ''
    } else {
        for (var i = 0; i < value.length; i++) {
            var op = value[i].split(':');
            if (op[0] == 'review') {    // 查看附件按钮
                if (row.attachCount >= 1) {
                    // 有附件
                    html += '<a class="btn ' + btnColors[op[0]] + ' btn-xs ' + 'btn-' + op[0] + ' ">' + operations[op[0]] + '<span>(' + row.attachCount + ')</span>' + '</a>';
                } else {
                    // 无附件
                    html += '<a class="btn ' + btnColors[op[0]] + ' btn-xs ' + 'btn-' + op[0] + ' disabled">' + operations[op[0]] + '<span>(' + 0 + ')</span>' + '</a>';
                }
            } else {    // 其他按钮
                if (op[1] == '0') {
                    // 禁用按钮
                    html += '<a class="btn ' + btnColors[op[0]] + ' btn-xs ' + 'btn-' + op[0] + ' disabled">' + operations[op[0]] + '</a>';
                } else if (op[1] == '1') {
                    // 可用按钮
                    html += '<a class="btn ' + btnColors[op[0]] + ' btn-xs ' + 'btn-' + op[0] + '">' + operations[op[0]] + '</a>';
                }

            }
        }
        return html;
    }
}

// 格式化时间
function dateFormatter(value, row, index) {
    return value ? value : '';
}

function onlyNumber(obj) {

    //得到第一个字符是否为负号    
    var t = obj.value.charAt(0);
    //先把非数字的都替换掉，除了数字和.和-号    
    obj.value = obj.value.replace(/[^\d\.\-]/g, '');
    //前两位不能是0加数字      
    obj.value = obj.value.replace(/^0\d[0-9]*/g, '');
    //必须保证第一个为数字而不是.       
    obj.value = obj.value.replace(/^\./g, '');
    //保证只有出现一个.而没有多个.       
    obj.value = obj.value.replace(/\.{2,}/g, '.');
    //保证.只出现一次，而不能出现两次以上       
    obj.value = obj.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
    //如果第一位是负号，则允许添加    
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
    if (t == '-') {
        return false;
    } else {
        return true;
    }
}

//+---------------------------------------------------
//| 字符串转成日期类型
//| 格式 MM/dd/YYYY MM-dd-YYYY YYYY/MM/dd YYYY-MM-dd
//+---------------------------------------------------
function StringToDate(DateStr) {

    var converted = Date.parse(DateStr);
    var myDate = new Date(converted);
    if (isNaN(myDate)) {
        var arys = DateStr.split('-');
        myDate = new Date(arys[0], --arys[1], arys[2]);
    }
    return myDate;
}

//格式化所属区域
function getArea(str) {
    console.log(str)
    var area = str.split(',');
    var areaTextArr = [];
    for (var i = 0; i < area.length; i++) {
        areaTextArr.push(areaList[area[i]]);
    }
    return areaTextArr.join(',');
};

// 格式化状态
function statusFormatter(value, row, index) {
    var spanHtml = '';
    switch (parseInt(value)) {
        case 0:
            spanHtml = '<span class="label label-primary">已提交</span>';
            break;
        case 1:
            spanHtml = '<span class="label label-success">已完成</span>';
            break;
        case 2:
            spanHtml = '<span class="label label-danger" onclick="delete_tag(' + row.id + ')">已驳回</span>';
            break;
        case 3:
            spanHtml = '<span class="label label-info">进行中</span>';
            break;
        case 4:
            spanHtml = '<span class="label label-warning">未开始</span>';
            break;
    }
    return spanHtml;
}

function delete_tag(row) {
    $.get(baseURL + "generator/pojecttask/queryReject/" + row, {token: token}, function (r) {
        if (r.code == '0' && !isBlank(r.src)) {
            alert(r.src);
        }
    });
}

// 检测对象类型
function type(obj) {
    return Object.prototype.toString.call(obj).replace(/\[object (\w+)\]/, '$1').toLowerCase();
}

// 获取项目ID
function getProjectId(src) {
    console.log(src);
    var qs = src.split('?')[1];
    var args = {};
    var items = qs.length ? qs.split('&') : [];
    console.log(items);
    var len = items.length;
    if (qs.length == 0) {
        // alert("没有查询字符串,退出！");
        return;
    }
    for (var i = 0; i < len; i++) {
        var item = items[i].split("=");
        args[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
    }
    return args;
}

// 格式化附件名称
function operateName(value, row, index) {
    console.log(row);
    return '<a class="btn-operate" href="' + row.attachPath + '" target="_blank">' + row.operationName + '</a>';
}

// 判断是否是当前项目的经理
function judgePm(userId, pId, roleIdList) {
    if (roleIdList.indexOf(6) != -1) {
        return 3;
    } else {
        if (userId == pId) {    // 项目经理
            return 1;
        } else {    // 项目负责人
            return 2;
        }
    }

}

//渲染会议纪要列表
function createSummary(id) {
    $("#jqGridMeeting").jqGrid({
        url: baseURL + 'generator/conferencesummary/queryProjectIdList',
        postData: {
            'projectId': id,
            'token': token
        },
        datatype: "json",
        colModel: [
            {label: '会议时间', name: 'conferenceTime', index: 'conference_time'},
            {label: '会议主题', name: 'conferenceTheme', index: 'conference_theme'},
            {
                label: '操作', name: 'endTime', formatter: function (value, options, row) {
                    // console.log('当前会议id' + row.id);
                    return '<a class="btn-uploadMeeting" href="javascript:void(0);" data-id="' + row.id + '">' + '上传纪要' + '</a>  ' +
                        '<a class="btn-detailsMeeting" href="javascript:void(0);" data-id="' + row.id + '">' + '详情' + '</a>';
                }
            }
        ],
        //pgbuttons:true,
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: false,
        rownumWidth: 25,
        autowidth: true,
        multiselect: false,
        // pager: "#jqGridPagerMeeting",
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGridMeeting").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            //
            $(".btn-uploadMeeting").on('click', function () {
                var conference = $(this).attr('data-id');
                var workitemHTML = '<div class="upload-box">' +
                    '<form class="file-loading" id="form1" method="post" enctype="multipart/form-data">' +
                    '<input id="file-meeting" class="" type="file" name="file">' +
                    '</form>' +
                    '</div>';
                layer.open({
                    type: 1,
                    skin: 'layui-layer-demo', //样式类名
                    closeBtn: 1, //显示关闭按钮
                    anim: 2,
                    area: ['500px', '120px'],
                    shadeClose: true, //开启遮罩关闭
                    content: workitemHTML
                });
                $("#file-meeting").fileinput({
                    // showUpload: false,
                    // showRemove: false,
                    uploadAsync: true,
                    showPreview: false,
                    language: 'zh',
                    textEncoding: "UTF-8",
                    uploadUrl: baseURL + "generator/conferencesummary/upload",
                    maxFileSize: 16300, /*设置允许图片大小单位KB*/
                    maxFileCount: 1, /*允许最大上传数，可以多个，当前设置单个*/
                    enctype: 'multipart/form-data',
                    // allowedFileExtensions: ["jpg", "png", "gif", "pdf"], /*上传文件格式*/
                    msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
                    dropZoneTitle: "请通过拖拽图片文件放到这里",
                    dropZoneClickTitle: "或者点击此区域添加图片",
                    uploadExtraData: function (previewId, index) {
                        var data = {
                            conferenceId: conference,
                            token: token,
                            creationUser: user.userId,
                            conferenceMesgAccessory: '2'
                        };
                        return data;
                    },//这个是外带数据
                    // showBrowse: false,
                    browseOnZoneClick: true,
                    slugCallback: function (filename) {
                        return filename.replace('(', '_').replace(']', '_');
                    }
                });
            });
            //查看详情
            $(".btn-detailsMeeting").on('click', function () {
                var conference = $(this).attr('data-id');
                var pWindow = window.parent;
                pWindow.indexVm.main = 'modules/project/conferenceaccessory.html?conferenceId=' + conference + '&projectId=' + id;
                pWindow.location.hash = 'modules/project/conferenceaccessory.html?conferenceId=' + conference + '&projectId=' + id;
            });
        }
    });
};

//统计收付款总额
function createPayment(id) {
    var data = {
        projectId: id
    };
    var projectApplicantList = [];
    /* 项目申请方列表 */
    $.get(baseURL + 'generator/projectapplicantinfo/alllist', function (result) {
        console.log(result);
        projectApplicantList = result.applicantList;
        //_this.projectEntity.projectApplicant = _this.projectApplicantList[0].id;
        //项目申请方
        $('#projectApplicant').select2({
            data: result.applicantList,
            placeholder: '请选择项目申请方',//默认文字提示
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            multiple: false
        });
        $("#projectApplicant").val("").select2();

    });
    $.ajax({
        type: "POST",
        headers: {
            token: "" + token
        },
        url: baseURL + "contract/contractreceipt/queryPaymenAmount",
        contentType: "application/json",
        data: JSON.stringify(data),
        success: function (r) {
            console.log(r.contractReceipt.receiptMoney);
            if (!r.contractReceipt.receiptMoney) {
                var paymentSum = 0
            } else {
                var paymentSum = r.contractReceipt.receiptMoney;
            }
            if (!r.contractReceipt.paymentMoney) {
                var receivablesSum = 0
            } else {
                var receivablesSum = r.contractReceipt.paymentMoney;
            }
            if(paymentSum!=0){
                var proportion = receivablesSum/paymentSum;
                proportion = parseInt(proportion*100);
            }else {
                var proportion = 0
            }
            $('#receivablesSum').html(paymentSum);
            $('#paymentSum').html(receivablesSum);
            $('#proportion').html(proportion+"%");
        }
    });

    //查看收复款情况
    $("#listsg11").jqGrid({
        url: baseURL + 'contract/contractreceipt/getContractReceipt',
        postData: {
            'projectId': id,
            'token': token
        },
        datatype: "json",
        colNames: ['合同名称', '报装单位', '合同金额', '决算金额', '招标批次', '收款金额', '收款比例', '总付款金额', '占收款比例', '操作'],
        // colNames: ['合同名称', '操作'],
        colModel: [
            {
                name: 'contractType',
                index: 'contractType',
                width: 200,
                align: "center",
                formatter: function (value, options, row) {
                    if (value == null) {
                        value = '';
                    }
                    return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;" title="' + value + '">' + value + '</div>';
                }
            },
            {
                name: 'reportingUnit',
                index: 'reportingUnit',
                width: 300,
                align: "center",
                formatter: function (value, options, row) {
                    if (value == null) {
                        value = '';
                    }
                    return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis" title="' + value + '">' + value + '</div>';
                }
            },
            {
                name: 'contractTotal',
                index: 'contractTotal',
                width: 150,
                align: "center",
                formatter: function (value, options, row) {
                    if (value == null) {
                        value = '';
                    }
                    return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis" title="' + value + '">' + value + '</div>';
                }
            },
            {
                name: 'settlementMoney',
                index: 'settlementMoney',
                width: 150,
                align: "center",
                formatter: function (value, options, row) {
                    if (value == null) {
                        value = '';
                    }
                    return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis" title="' + value + '">' + value + '</div>';
                }
            },
            {name: 'tenderBatch', index: 'tenderBatch', width: 150, align: "center"},
            {
                name: 'receiptMoney',
                index: 'receiptMoney',
                width: 150,
                align: "center",
                formatter: function (value, options, row) {
                    if (value == null) {
                        value = '';
                    }
                    return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis" title="' + value + '">' + value + '</div>';
                }
            },
            {name: 'receiptScale', index: 'receiptScale', width: 150, align: "center"},
            {
                name: 'paymentMoney',
                index: 'paymentMoney',
                width: 150,
                align: "center",
                formatter: function (value, options, row) {
                    if (value == null) {
                        value = '';
                    }
                    return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis" title="' + value + '">' + value + '</div>';
                }
            },
            {name: 'paymentScale', index: 'paymentScale', width: 150, align: "center"},
            {
                name: 'end', index: 'end', width: 300, formatter: function (value, options, row) {
                    // console.log('当前会议id' + row.id);
                    return '<a class="btn-updatePayment" href="javascript:void(0);" data-id="' + row.id + '"' +
                        ' data-reportingUnit="' + row.reportingUnit + '"' + ' data-contractTotal="' + row.contractTotal + '"' +
                        ' data-settlementMoney="' + row.settlementMoney + '"' + ' data-tenderBatch="' + row.tenderBatch + '"' + ' data-receiptMoney="' + row.receiptMoney + '">' + '修改' + '</a>&nbsp;&nbsp;' +
                        '<a class="btn-svnPayment" href="javascript:void(0);" data-id="' + row.id + '"  data-projectId="' + row.projectId + '">' + '新增子合同' + '</a>&nbsp;&nbsp;' +
                        '<a class="btn-svnReceipt" href="javascript:void(0);" data-id="' + row.id + '"  data-projectId="' + row.projectId + '">' + '新增收款' + '</a>&nbsp;&nbsp;' +
                        '<a class="btn-queryReceipt" href="javascript:void(0);" data-id="' + row.id + '"  data-projectId="' + row.projectId + '">' + '收款详情' + '</a>';
                }
            }
        ],
        width: 1200,
        height: 400,
        rowNum: 8,
        rowList: [8, 10, 20, 30],
        pager: '#pagersg11',
        viewrecords: true,
        multiselect: false,
        subGrid: true,
        subGridOptions: {
            "openicon": ''
        },
        gridComplete: function () {
            var taskList = [];
            //查询招标批次
            $.get(baseURL + 'contract/tenderingbatch/queryInfo', function (result) {
                console.log(result);
                taskList = result.tenderingBatch;
            });
            //修改收款合同
            $(".btn-updatePayment").on('click', function () {
               /* alert("111");
                return;*/
                //查询招标批次及有几个合同挂在此批次下
                /* 项目申请方列表 */
                $.get(baseURL + 'generator/projectapplicantinfo/alllist', function (result) {
                    console.log(result);
                    projectApplicantList = result.applicantList;
                    //_this.projectEntity.projectApplicant = _this.projectApplicantList[0].id;
                    //项目申请方
                    $('#reportingUnit').select2({
                        data: result.applicantList,
                        placeholder: '请选择项目申请方',//默认文字提示
                        language: "zh-CN",//汉化
                        allowClear: true,//允许清空
                        multiple: false,
                        tags: true
                    });
                    // $("#reportingUnit").val("").select2();


                });

                var receiptId = $(this).attr('data-id');
                if ($(this).attr('data-reportingUnit') != null && $(this).attr('data-reportingUnit') != 'null') {
                    var reportingUnit = $(this).attr('data-reportingUnit');
                } else {
                    var reportingUnit = '';
                }
                if ($(this).attr('data-contractTotal') != null && $(this).attr('data-contractTotal') != 'null') {
                    var contractTotal = $(this).attr('data-contractTotal');
                } else {
                    var contractTotal = '';
                }
                if ($(this).attr('data-settlementMoney') != null && $(this).attr('data-settlementMoney') != 'null') {
                    var settlementMoney = $(this).attr('data-settlementMoney');
                } else {
                    var settlementMoney = '';
                }
                if ($(this).attr('data-tenderBatch') != null && $(this).attr('data-tenderBatch') != 'null') {
                    var tenderBatch = $(this).attr('data-tenderBatch');
                } else {
                    var tenderBatch = '';
                }
                if ($(this).attr('data-receiptMoney') != null && $(this).attr('data-receiptMoney') != 'null') {
                    var receiptMoney = $(this).attr('data-receiptMoney');
                } else {
                    var receiptMoney = '';
                }
                console.log(taskList);
                var tenderBatchOption = '';
                for (var i = 0; i < taskList.length; i++) {
                    tenderBatchOption += '<option value="' + taskList[i].id + '">' + taskList[i].batchNumber + '</option>';
                }
                var updataprojectPaymentHTML = '<div class="layer-form-content">' +
                    '<div class="layer-input-container">' +
                    '<div class="layer-input-cell">' +
                    '<div class="col-sm-4 control-label">报装单位</div>' +
                    '<div class="col-sm-8">' +
                    ' <select class="form-control" id="reportingUnit" multiple="multiple"' +
                    ' data-placeholder="报装单位"' +
                    ' style="width: 100%;">' +
                    '</select>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-input-cell">' +
                    '<div class="col-sm-4 control-label">合同金额</div>' +
                    '<div class="col-sm-8">' +
                    '<input type="text" value="' + contractTotal + '" class="form-control" id="contractTotal" placeholder="合同金额"/>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-input-cell">' +
                    '<div class="col-sm-4 control-label">决算金额</div>' +
                    '<div class="col-sm-8">' +
                    '<input type="text" value="' + settlementMoney + '" class="form-control" id="settlementMoney" placeholder="决算金额" onkeyup= "onlyNumber(this)"/>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-input-cell">' +
                    '<div class="col-sm-4 control-label">招标批次</div>' +
                    '<div class="col-sm-8">' +
                    /* '<input type="text" value="' + tenderBatch + '" class="form-control" id="tenderBatch" placeholder="招标批次"/>' +*/
                    '<select class="form-control" id = "tenderBatch">' +
                    tenderBatchOption +
                    '</select>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-operate-container">' +
                    '<input type="button" class="btn btn-primary" id="updatePayment" value="提交"/>' +
                    '</div>' +
                    '</div>';
                layer.open({
                    title: '修改合同',
                    type: 1,
                    skin: 'layui-layer-demo', //样式类名
                    closeBtn: 1, //显示关闭按钮
                    anim: 2,
                    area: ['400px', '310px'],
                    shadeClose: true, //开启遮罩关闭
                    content: updataprojectPaymentHTML
                });
                $('#contractTotal').on('input', function () {
                    var flag = onlyNumber(this);
                    if (flag) {
                        var contractTotalTemp = $(this).val();
                        settlementMoney = contractTotalTemp;
                        $('#settlementMoney').val(settlementMoney);
                        console.log(contractTotalTemp);
                    } else {
                        return false;
                    }
                });

                $('#updatePayment').on('click', function () {
                    layer.closeAll('dialog');
                    var data = {
                        id: receiptId,
                        reportingUnit: $('#reportingUnit').val(),
                        contractTotal: $('#contractTotal').val(),
                        settlementMoney: $('#settlementMoney').val(),
                        tenderBatch: $('#tenderBatch').val(),
                        receiptMoney: $('#receiptMoney').val(),
                        projectId: id
                    };
                    console.log(data);
                    var data1 = {
                        contractReceiptId: receiptId,
                        money: "0"
                        //receiptDateSrc: $('#receiptDate').val()
                    };
                    $.ajax({
                        type: "POST",
                        url: baseURL + "contract/contractreceipt/earlyWarning",
                        headers: {'token': token},
                        contentType: "application/json",
                        data: JSON.stringify(data),
                        success: function (r) {
                            console.log(r);
                            if (r.code == 0) {
                              if (r.msg == '0'){
                                  confirm('该批次已超支付，确定要将该合同挂在该批次下吗？', function () {
                                      $.ajax({
                                          type: "POST",
                                          url: baseURL + "contract/contractreceipt/update",
                                          headers: {'token': token},
                                          contentType: "application/json",
                                          data: JSON.stringify(data),
                                          success: function (r) {
                                              if (r.code == 0) {
                                                  $.ajax({
                                                      type: "POST",
                                                      url: baseURL + "contract/contractreceiptinfo/save",
                                                      headers: {'token': token},
                                                      contentType: "application/json",
                                                      data: JSON.stringify(data1),
                                                      success: function (r) {
                                                          if (r.code == 0) {
                                                          } else {
                                                              alert(r.msg);
                                                          }
                                                      }
                                                  });
                                                  alert('操作成功', function (index) {
                                                      layer.closeAll();
                                                      var pWindow = window.parent;
                                                      var oIframe = $('#main-content iframe', pWindow.document);
                                                      oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                                                  });
                                              } else {
                                                  alert(r.msg);
                                              }
                                          }
                                      });
                                  });
                              } else {
                                  $.ajax({
                                      type: "POST",
                                      url: baseURL + "contract/contractreceipt/update",
                                      headers: {'token': token},
                                      contentType: "application/json",
                                      data: JSON.stringify(data),
                                      success: function (r) {
                                          if (r.code == 0) {
                                              $.ajax({
                                                  type: "POST",
                                                  url: baseURL + "contract/contractreceiptinfo/save",
                                                  headers: {'token': token},
                                                  contentType: "application/json",
                                                  data: JSON.stringify(data1),
                                                  success: function (r) {
                                                      if (r.code == 0) {
                                                      } else {
                                                          alert(r.msg);
                                                      }
                                                  }
                                              });
                                              alert('操作成功', function (index) {
                                                  layer.closeAll();
                                                  var pWindow = window.parent;
                                                  var oIframe = $('#main-content iframe', pWindow.document);
                                                  oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                                              });
                                          } else {
                                              alert(r.msg);
                                          }
                                      }
                                  });
                              }
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                    return;
                    confirm('确定要将改合同挂在改批次下吗？', function () {
                        $.ajax({
                            type: "POST",
                            url: baseURL + "contract/contractreceipt/update",
                            headers: {'token': token},
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            success: function (r) {
                                if (r.code == 0) {
                                    $.ajax({
                                        type: "POST",
                                        url: baseURL + "contract/contractreceiptinfo/save",
                                        headers: {'token': token},
                                        contentType: "application/json",
                                        data: JSON.stringify(data1),
                                        success: function (r) {
                                            if (r.code == 0) {
                                            } else {
                                                alert(r.msg);
                                            }
                                        }
                                    });
                                    alert('操作成功', function (index) {
                                        layer.closeAll();
                                        var pWindow = window.parent;
                                        var oIframe = $('#main-content iframe', pWindow.document);
                                        oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                                    });
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    });

                });
            });
            /* });*/
            //新增子合同
            $(".btn-svnPayment").on('click', function () {
                var contractReceiptId = $(this).attr('data-id');
                var projectId = $(this).attr('data-projectId');
                console.log(contractReceiptId);
                /* 项目申请方列表 */
                $.get(baseURL + 'generator/projectapplicantinfo/alllist', function (result) {
                    console.log(result);
                    projectApplicantList = result.applicantList;
                    //_this.projectEntity.projectApplicant = _this.projectApplicantList[0].id;
                    //项目申请方
                    $('#reportingUnit').select2({
                        data: result.applicantList,
                        placeholder: '请选择施工单位',//默认文字提示
                        language: "zh-CN",//汉化
                        allowClear: true,//允许清空
                        multiple: false,
                        tags: true
                    });
                });
                var updataprojectPaymentHTML =
                    '<div class="form-group">' +
                    '    <div class="col-sm-4 control-label">合同编号</div>' +
                    '    <div class="col-sm-8">' +
                    '        <input type="text" class="form-control" id="contractNumber" placeholder="合同编号"/>' +
                    '    </div>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '    <div class="col-sm-4 control-label">合同名称</div>' +
                    '    <div class="col-sm-8">' +
                    '        <input type="text" class="form-control" id="contractName" placeholder="合同名称"/>' +
                    '    </div>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '    <div class="col-sm-4 control-label">施工单位</div>' +
                    '    <div class="col-sm-8">' +
                    ' <select class="form-control" id="reportingUnit" multiple="multiple"' +
                    ' data-placeholder="施工单位"' +
                    ' style="width: 100%;">' +
                    '</select>' +
                    '    </div>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '    <div class="col-sm-4 control-label">合同金额</div>' +
                    '    <div class="col-sm-8">' +
                    '        <input type="text"  class="form-control" id="contractTotal" placeholder="合同金额" onkeyup= "onlyNumber(this)"/>' +
                    '    </div>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '    <div class="col-sm-4 control-label">决算金额</div>' +
                    '    <div class="col-sm-8">' +
                    '        <input type="text"  class="form-control" id="settlementMoney" placeholder="决算金额" onkeyup= "onlyNumber(this)"/>' +
                    '    </div>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '    <div class="col-sm-4 control-label">招标批次</div>' +
                    '    <div class="col-sm-8">' +
                    '        <input type="text"  class="form-control" id="tenderBatch" placeholder="招标批次"/>' +
                    '    </div>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '    <div class="col-sm-4 control-label">合同签订时间</div>' +
                    '<div class="col-sm-8">' +
                    '    <input type="text" ref="input1"  class="form-control" id="contractTime" placeholder="合同时间" name="conferenceTime">' +
                    '    </div>' +
                    '</div>' +
                    '</form>' +
                    '<div class="form-group">' +
                    ' <div class="col-sm-6 control-label"></div>' +
                    '  <input type="button" class="btn btn-primary" id="svnPayment" value="提交"/>' +
                    ' </div>' +
                    '</form>';
                updataprojectPaymentHTML = '<div class="layer-form-content">' +
                    '<div class="layer-input-container layer-contract-input-container">' +
                    '<div class="layer-input-cell">' +
                    '<div class="col-sm-4 control-label">合同编号</div>' +
                    '<div class="col-sm-8">' +
                    '<input type="text" class="form-control" id="contractNumber" placeholder="合同编号"/>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-input-cell">' +
                    '<div class="col-sm-4 control-label">合同名称</div>' +
                    '<div class="col-sm-8">' +
                    '<input type="text" class="form-control" id="contractName" placeholder="合同名称"/>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-input-cell">' +
                    '<div class="col-sm-4 control-label">施工单位</div>' +
                    '<div class="col-sm-8">' +
                    ' <select class="form-control" id="reportingUnit" multiple="multiple"' +
                    ' data-placeholder="施工单位"' +
                    ' style="width: 100%;">' +
                    '</select>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-input-cell">' +
                    '<div class="col-sm-4 control-label">合同金额</div>' +
                    '<div class="col-sm-8">' +
                    '<input type="text"  class="form-control" id="contractTotal" placeholder="合同金额"/>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-input-cell">' +
                    '<div class="col-sm-4 control-label">决算金额</div>' +
                    '<div class="col-sm-8">' +
                    '<input type="text"  class="form-control" id="settlementMoney" placeholder="决算金额" onkeyup= "onlyNumber(this)"/>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-input-cell">' +
                    '<div class="col-sm-4 control-label">招标批次</div>' +
                    '<div class="col-sm-8">' +
                    '<input type="text"  class="form-control" id="tenderBatch" placeholder="招标批次"/>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-input-cell">' +
                    '<div class="col-sm-4 control-label">合同签订时间</div>' +
                    '<div class="col-sm-8">' +
                    '<input type="text" ref="input1"  class="form-control" id="contractTime" placeholder="合同时间" name="conferenceTime">' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-operate-container">' +
                    '<input type="button" class="btn btn-primary" id="svnPayment" value="提交"/>' +
                    '</div>' +
                    '</div>';


                var myDate = new Date();
                var time = myDate.toLocaleDateString().split('/').join('-');
                $('#contractTime').value = time;
                layer.open({
                    title: '新增子合同',
                    type: 1,
                    skin: 'layui-layer-demo', //样式类名
                    closeBtn: 1, //显示关闭按钮
                    anim: 2,
                    area: ['450px', '350px'],
                    shadeClose: true, //开启遮罩关闭
                    content: updataprojectPaymentHTML
                });

                $('#contractTotal').on('input', function () {
                    console.log(1);
                    // onkeyup= "getSettlementMoney(this, '+ contractTotal +')"
                    var flag = onlyNumber(this);
                    if (flag) {
                        var contractTotalTemp = $(this).val();
                        // settlementMoney = contractTotalTemp;
                        $('#settlementMoney').val(contractTotalTemp);
                        console.log(contractTotalTemp);
                    } else {
                        return false;
                    }
                });

                // 时间控件
                $('#contractTime').datetimepicker({
                    language: 'zh-CN',
                    format: 'yyyy-mm-dd',
                    initialDate: new Date(),
                    todayHighlight: 1,
                    showMeridian: 0,
                    autoclose: 1,
                    minView: 2
                });
                $('#svnPayment').on('click', function () {
                    var bagin = $('#contractTime').val();
                    var bagin_r = bagin.match(/^(\d{4})(-)(\d{2})(-)(\d{2})$/);
                    if (bagin_r == null) {
                        alert("请输入正确的开始时间格式");
                        return false;
                    }
                    layer.closeAll('dialog');
                    var data = {
                        projectId: projectId,
                        contractReceiptId: contractReceiptId,
                        contractNumber: $('#contractNumber').val(),
                        contractName: $('#contractName').val(),
                        reportingUnit: $('#reportingUnit').val(),
                        contractTotal: $('#contractTotal').val(),
                        settlementMoney: $('#settlementMoney').val(),
                        tenderBatch: $('#tenderBatch').val(),
                        contractTimeStr: $('#contractTime').val(),
                    };
                    console.log(data);
                    $.ajax({
                        type: "POST",
                        url: baseURL + "contract/contractpayment/save",
                        headers: {'token': token},
                        contentType: "application/json",
                        data: JSON.stringify(data),
                        success: function (r) {
                            if (r.code == 0) {
                                alert('操作成功', function (index) {
                                    layer.closeAll();
                                    var pWindow = window.parent;
                                    var oIframe = $('#main-content iframe', pWindow.document);
                                    oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                                });
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                });
            });
            //删除收款合同
            $(".btn-deletePayment").on('click', function () {
                var receiptId = $(this).attr('data-id');
                console.log(receiptId);
                var data = {
                    id: receiptId,
                    projectId: id
                };
                $.ajax({
                    type: "POST",
                    url: baseURL + "contract/contractreceipt/deleteContractReceipt",
                    headers: {'token': token},
                    contentType: "application/json",
                    data: JSON.stringify(data),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                layer.closeAll();
                                var pWindow = window.parent;
                                var oIframe = $('#main-content iframe', pWindow.document);
                                oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
            //新增收款
            $(".btn-svnReceipt").on('click', function () {
                var receiptId = $(this).attr('data-id');
                console.log(receiptId);
                var updataprojectPaymentHTML = '<div class="layer-form-content">' +
                    '<div class="layer-input-container">' +
                    '<div class="layer-input-cell form-group">' +
                    '<div class="col-sm-4 control-label">收款金额</div>' +
                    '<div class="col-sm-8">' +
                    '<input type="text" class="form-control" id="money" placeholder="收款金额"/>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-input-cell form-group">' +
                    '<div class="col-sm-4 control-label">收款时间</div>' +
                    '<div class="col-sm-8">' +
                    '<input type="text" class="form-control" id="receiptDate" placeholder="收款时间" name="conferenceTime"/>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layer-operate-container">' +
                    '<input type="button" class="btn btn-primary" id="insertPaymentInfo" value="提交"/>' +
                    '</div>' +
                    '</div>';
                layer.open({
                    title: '新增收款',
                    type: 1,
                    skin: 'layui-layer-demo', //样式类名
                    closeBtn: 1, //显示关闭按钮
                    anim: 2,
                    area: ['400px', '310px'],
                    shadeClose: true, //开启遮罩关闭
                    content: updataprojectPaymentHTML
                });
                // 时间控件
                $('#receiptDate').datetimepicker({
                    language: 'zh-CN',
                    format: 'yyyy-mm-dd',
                    initialDate: new Date(),
                    todayHighlight: 1,
                    showMeridian: 0,
                    autoclose: 1,
                    minView: 2
                });
                $('#insertPaymentInfo').on('click', function () {

                    var bagin = $('#receiptDate').val();
                    var bagin_r = bagin.match(/^(\d{4})(-)(\d{2})(-)(\d{2})$/);
                    if (bagin_r == null) {
                        alert("请输入正确的时间格式");
                        return false;
                    }

                    layer.closeAll('dialog');
                    var data = {
                        contractReceiptId: receiptId,
                        money: $('#money').val(),
                        receiptDateSrc: $('#receiptDate').val()
                    };
                    $.ajax({
                        type: "POST",
                        url: baseURL + "contract/contractreceiptinfo/save",
                        headers: {'token': token},
                        contentType: "application/json",
                        data: JSON.stringify(data),
                        success: function (r) {
                            if (r.code == 0) {
                                alert('操作成功', function (index) {
                                    layer.closeAll();
                                    var pWindow = window.parent;
                                    var oIframe = $('#main-content iframe', pWindow.document);
                                    oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                                });
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                });
            });
            //收款详情
            $(".btn-queryReceipt").on('click', function () {
                var receiptId = $(this).attr('data-id');
                console.log(receiptId);
                var updataprojectPaymentHTML = '<table id="jqGridPaymentInfo"></table>';
                layer.open({
                    title: '收款详情',
                    type: 1,
                    skin: 'layui-layer-demo', //样式类名
                    closeBtn: 1, //显示关闭按钮
                    anim: 2,
                    area: ['520px', '400px'],
                    shadeClose: true, //开启遮罩关闭
                    content: updataprojectPaymentHTML
                });
                $("#jqGridPaymentInfo").jqGrid({
                    url: baseURL + 'contract/contractreceiptinfo/list',
                    postData: {
                        contractReceiptId: receiptId
                    },
                    headers: {'token': token},
                    datatype: "json",
                    colModel: [
                        {label: '收款金额', name: 'money', width: 75, align: "center"},
                        {label: '收款时间', name: 'receiptDate', width: 75, align: "center"},
                        {
                            label: '操作',
                            name: 'createTime',
                            index: "create_time",
                            width: 90,
                            formatter: function (value, options, row) {
                                return '<a class="btn-deletePaymentProportionInfo" href="javascript:void(0);" data-id="' + row.id + '">' + '删除' + '</a>';
                            }
                        }
                    ],
                    viewrecords: true,
                    height: 300,
                    rowNum: 10,
                    rowList: [10, 30, 50],
                    rownumbers: true,
                    rownumWidth: 25,
                    autowidth: true,
                    multiselect: false,
                    pager: "#jqGridPagerPaymentInfo",
                    jsonReader: {
                        root: "page.list",
                        page: "page.currPage",
                        total: "page.totalPage",
                        records: "page.totalCount"
                    },
                    prmNames: {
                        page: "page",
                        rows: "limit",
                        order: "order"
                    },
                    gridComplete: function () {
                        //隐藏grid底部滚动条
                        $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
                        $(".btn-deletePaymentProportionInfo").on('click', function () {
                            var paymentProportionInfoId = $(this).attr('data-id');
                            console.log(paymentProportionInfoId)
                            var data = {
                                id: paymentProportionInfoId
                            };

                            confirm('确定要删除本次收款吗？', function () {
                                $.ajax({
                                    type: "POST",
                                    url: baseURL + "contract/contractreceiptinfo/delete",
                                    headers: {'token': token},
                                    contentType: "application/json",
                                    data: JSON.stringify(data),
                                    success: function (r) {
                                        if (r.code == 0) {
                                            alert('操作成功', function (index) {
                                                layer.closeAll();
                                                var pWindow = window.parent;
                                                var oIframe = $('#main-content iframe', pWindow.document);
                                                oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                                            });
                                        } else {
                                            alert(r.msg);
                                        }
                                    }
                                });
                            });
                        });
                    }
                });
            });
        },
        subGridRowExpanded: function (subgrid_id, row_id) {
            console.log(row_id);
            var subgrid_table_id, pager_id;
            subgrid_table_id = subgrid_id + "_t";
            pager_id = "p_" + subgrid_table_id;

            $("#" + subgrid_id).html(
                "<div style='width: 100%; box-sizing: border-box;'><table id='" + subgrid_table_id
                + "' class='scroll'></table><div id='"
                + pager_id + "' class='scroll'></div></div>");
            $("#" + subgrid_table_id).jqGrid(
                {
                    url: baseURL + 'contract/contractreceipt/getContractPayment',
                    postData: {
                        'contractReceiptId': row_id,
                        'token': token
                    },
                    datatype: "json",
                    colNames: ['合同编号', '合同名称', '施工单位', '合同金额', '决算金额', '招标批次', '合同签订时间', '已付款金额', '已付款比例', '操作'],
                    colModel: [
                        {
                            name: "contractNumber",
                            index: "contractNumber",
                            width: 100,
                            align: "center",
                            sortable: false,
                            formatter: function (value, options, row) {
                                if (value == null) {
                                    value = '';
                                }
                                return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis" title="' + value + '">' + value + '</div>';
                            }
                        },
                        {
                            name: "contractName",
                            index: "contractName",
                            width: 200,
                            align: "center",
                            formatter: function (value, options, row) {
                                if (value == null) {
                                    value = '';
                                }
                                return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis" title="' + value + '">' + value + '</div>';
                            }
                        },
                        {
                            name: "reportingUnit",
                            index: "reportingUnit",
                            width: 200,
                            align: "center",
                            formatter: function (value, options, row) {
                                if (value == null) {
                                    value = '';
                                }
                                return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis" title="' + value + '">' + value + '</div>';
                            }
                        },
                        {
                            name: "contractTotal",
                            index: "contractTotal",
                            width: 100,
                            align: "center",
                            formatter: function (value, options, row) {
                                if (value == null) {
                                    value = '';
                                }
                                return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis" title="' + value + '">' + value + '</div>';
                            }
                        },
                        {
                            name: "settlementMoney",
                            index: "settlementMoney",
                            width: 100,
                            align: "center",
                            formatter: function (value, options, row) {
                                if (value == null) {
                                    value = '';
                                }
                                return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis" title="' + value + '">' + value + '</div>';
                            }
                        },
                        {name: "tenderBatch", index: "tenderBatch", width: 100, align: "center"},
                        {name: "contractTimeStr", index: "contractTimeStr", width: 100, align: "center"},
                        {
                            name: "paymentMoney",
                            index: "paymentMoney",
                            width: 100,
                            align: "center",
                            formatter: function (value, options, row) {
                                if (value == null) {
                                    value = '';
                                }
                                return '<div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis" title="' + value + '">' + value + '</div>';
                            }
                        },
                        {name: "paymentScale", index: "paymentScale", width: 100, align: "center"},
                        {
                            name: "end", index: "end", width: 300, formatter: function (value, options, row) {
                                // console.log('当前会议id' + row.id);
                                return '<a class="btn-updatePaymentInfo" href="javascript:void(0);" data-id="' + row.id + '" ' +
                                    ' data-contractNumber="' + row.contractNumber + '"  data-contractName="' + row.contractName + '"' +
                                    ' data-reportingUnit="' + row.reportingUnit + '" data-contractTotal="' + row.contractTotal + '"' +
                                    ' data-settlementMoney="' + row.settlementMoney + '" data-tenderBatch="' + row.tenderBatch + '">' + '修改' + '</a>&nbsp;&nbsp;' +
                                    '<a class="btn-svnPaymentInfo" href="javascript:void(0);" data-id="' + row.id + '" data-contractTotal="' + row.contractTotal + '">' + '新增支付' + '</a>&nbsp;&nbsp;' +
                                    '<a class="btn-getPaymentInfo" href="javascript:void(0);" data-id="' + row.id + '">' + '支付详情' + '</a>';
                            }
                        }
                    ],
                    rowNum: 5,
                    width: 1100,
                    pager: pager_id,
                    sortname: 'num',
                    sortorder: "asc",
                    height: '100%',
                    gridComplete: function () {
                        //修改付款合同
                        $(".btn-updatePaymentInfo").on('click', function () {
                            $.get(baseURL + 'generator/projectapplicantinfo/alllist', function (result) {
                                console.log(result);
                                projectApplicantList = result.applicantList;
                                //_this.projectEntity.projectApplicant = _this.projectApplicantList[0].id;
                                //项目申请方
                                $('#reportingUnit').select2({
                                    data: result.applicantList,
                                    placeholder: '请选择项目申请方',//默认文字提示
                                    language: "zh-CN",//汉化
                                    allowClear: true,//允许清空
                                    multiple: false,
                                    tags: true
                                });
                                //$("#reportingUnit").val("").select2();

                            });
                            var contractPaymentid = $(this).attr('data-id');
                            console.log(id);
                            if ($(this).attr('data-contractNumber') != null && $(this).attr('data-contractNumber') != 'null') {
                                var contractNumber = $(this).attr('data-contractNumber');
                            } else {
                                var contractNumber = '';
                            }
                            if ($(this).attr('data-contractName') != null && $(this).attr('data-contractName') != 'null') {
                                var contractName = $(this).attr('data-contractName');
                            } else {
                                var contractName = '';
                            }
                            if ($(this).attr('data-contractTotal') != null && $(this).attr('data-contractTotal') != 'null') {
                                var contractTotal = $(this).attr('data-contractTotal');
                            } else {
                                var contractTotal = '';
                            }
                            if ($(this).attr('data-reportingUnit') != null && $(this).attr('data-reportingUnit') != 'null') {
                                var reportingUnit = $(this).attr('data-reportingUnit');//施工单位
                            } else {
                                var reportingUnit = '';
                            }
                            if ($(this).attr('data-tenderBatch') != null && $(this).attr('data-tenderBatch') != 'null') {
                                var tenderBatch = $(this).attr('data-tenderBatch');
                            } else {
                                var tenderBatch = '';
                            }
                            if ($(this).attr('data-settlementMoney') != null && $(this).attr('data-settlementMoney') != 'null') {
                                var settlementMoney = $(this).attr('data-settlementMoney');
                            } else {
                                var settlementMoney = '';
                            }
                            var updataprojectPaymentHTML = '<div class="layer-form-content">' +
                                '<div class="layer-input-container">' +
                                '<div class="layer-input-cell">' +
                                '<div class="col-sm-4 control-label">合同编号</div>' +
                                '<div class="col-sm-8">' +
                                '<input type="text" class="form-control" value="' + contractNumber + '" id="contractNumber" placeholder="合同编号"/>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layer-input-cell">' +
                                '<div class="col-sm-4 control-label">合同名称</div>' +
                                '<div class="col-sm-8">' +
                                '<input type="text" value="' + contractName + '" class="form-control" id="contractName" placeholder="合同名称"/>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layer-input-cell">' +
                                '<div class="col-sm-4 control-label">合同金额</div>' +
                                '<div class="col-sm-8">' +
                                '<input type="text" value="' + contractTotal + '" class="form-control" id="contractTotal" placeholder="合同金额"/>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layer-input-cell">' +
                                '<div class="col-sm-4 control-label">决算金额</div>' +
                                '<div class="col-sm-8">' +
                                '<input type="text" value="' + settlementMoney + '" class="form-control" id="settlementMoney" placeholder="决算金额" onkeyup= "onlyNumber(this)"/>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layer-input-cell">' +
                                '<div class="col-sm-4 control-label">招标批次</div>' +
                                '<div class="col-sm-8">' +
                                '<input type="text" value="' + tenderBatch + '" class="form-control" id="tenderBatch" placeholder="招标批次"/>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layer-input-cell">' +
                                '<div class="col-sm-4 control-label">施工单位</div>' +
                                '<div class="col-sm-8">' +
                                ' <select  class="form-control" id="reportingUnit" multiple="multiple"' +
                                ' data-placeholder="报装单位"' +
                                ' style="width: 100%;">' +
                                '</select>' +
                                '</div>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layer-operate-container">' +
                                '<input type="button" class="btn btn-primary" id="updatePaymentInfo" value="提交"/>' +
                                '</div>' +
                                '</div>';
                            layer.open({
                                title: '修改合同',
                                type: 1,
                                skin: 'layui-layer-demo', //样式类名
                                closeBtn: 1, //显示关闭按钮
                                anim: 2,
                                area: ['400px', '310px'],
                                shadeClose: true, //开启遮罩关闭
                                content: updataprojectPaymentHTML
                            });

                            $('#contractTotal').on('input', function () {
                                console.log(1);
                                var flag = onlyNumber(this);
                                if (flag) {
                                    var contractTotalTemp = $(this).val();
                                    settlementMoney = contractTotalTemp;
                                    $('#settlementMoney').val(settlementMoney);
                                    console.log(contractTotalTemp);
                                } else {
                                    return false;
                                }
                            });

                            $('#updatePaymentInfo').on('click', function () {
                                layer.closeAll('dialog');
                                var data = {
                                    id: contractPaymentid,
                                    contractNumber: $('#contractNumber').val(),
                                    contractName: $('#contractName').val(),
                                    contractTotal: $('#contractTotal').val(),
                                    reportingUnit: $('#reportingUnit').val(),
                                    tenderBatch: $('#tenderBatch').val(),
                                    settlementMoney: $('#settlementMoney').val()
                                };
                                var contractPaymentId = $(this).attr('data-id');
                                var contractTotal = $(this).attr('data-contractTotal');
                                var data1 = {
                                    contractPaymentId: contractPaymentId,
                                    paymentMoney: "0",
                                    //paymentTimeStr: $('#paymentTime').val(),
                                    contractTotal: contractTotal,
                                    projectId: id
                                };
                                console.log(data);
                                $.ajax({
                                    type: "POST",
                                    url: baseURL + "contract/contractpayment/update",
                                    headers: {'token': token},
                                    contentType: "application/json",
                                    data: JSON.stringify(data),
                                    success: function (r) {
                                        if (r.code == 0) {
                                            alert('操作成功', function (index) {
                                                layer.closeAll();
                                                var pWindow = window.parent;
                                                var oIframe = $('#main-content iframe', pWindow.document);
                                                oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                                            });
                                        } else {
                                            alert(r.msg);
                                        }
                                    }
                                });
                            });

                        });
                        //新增支付
                        $(".btn-svnPaymentInfo").on('click', function () {
                            var contractPaymentId = $(this).attr('data-id');
                            var contractTotal = $(this).attr('data-contractTotal');
                            console.log(contractPaymentId);
                            var updataprojectPaymentHTML = '<div class="layer-form-content">' +
                                '<div class="layer-input-container">' +
                                '<div class="layer-input-cell form-group">' +
                                '<div class="col-sm-4 control-label">支付金额</div>' +
                                '<div class="col-sm-8">' +
                                '<input type="text" class="form-control" id="paymentMoney" placeholder="支付金额"/>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layer-input-cell form-group">' +
                                '<div class="col-sm-4 control-label">支付时间</div>' +
                                '<div class="col-sm-8">' +
                                '<input type="text" class="form-control" id="paymentTime" placeholder="支付时间" name="conferenceTime"/>' +
                                '</div>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layer-operate-container">' +
                                '<input type="button" class="btn btn-primary" id="insertPaymentInfo" value="提交"/>' +
                                '</div>' +
                                '</div>';
                            layer.open({
                                title: '新增支付',
                                type: 1,
                                skin: 'layui-layer-demo', //样式类名
                                closeBtn: 1, //显示关闭按钮
                                anim: 2,
                                area: ['400px', '310px'],
                                shadeClose: true, //开启遮罩关闭
                                content: updataprojectPaymentHTML
                            });
                            // 时间控件
                            $('#paymentTime').datetimepicker({
                                language: 'zh-CN',
                                format: 'yyyy-mm-dd',
                                initialDate: new Date(),
                                todayHighlight: 1,
                                showMeridian: 0,
                                autoclose: 1,
                                minView: 2
                            });
                            $('#insertPaymentInfo').on('click', function () {

                                var bagin = $('#paymentTime').val();
                                var bagin_r = bagin.match(/^(\d{4})(-)(\d{2})(-)(\d{2})$/);
                                if (bagin_r == null) {
                                    alert("请输入正确的开始时间格式");
                                    return false;
                                }

                                layer.closeAll('dialog');
                                var data = {
                                    contractPaymentId: contractPaymentId,
                                    paymentMoney: $('#paymentMoney').val(),
                                    paymentNumber: $('#paymentNumber').val(),
                                    paymentTimeStr: $('#paymentTime').val(),
                                    contractTotal: contractTotal,
                                    projectId: id
                                };
                                console.log(data);
                                $.ajax({
                                    type: "POST",
                                    url: baseURL + "contract/paymentinfo/save",
                                    headers: {'token': token},
                                    contentType: "application/json",
                                    data: JSON.stringify(data),
                                    success: function (r) {
                                        if (r.code == 0) {
                                            alert('操作成功', function (index) {
                                                layer.closeAll();
                                                var pWindow = window.parent;
                                                var oIframe = $('#main-content iframe', pWindow.document);
                                                oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                                            });
                                        } else {
                                            alert(r.msg);
                                        }
                                    }
                                });
                            });

                        });
                        //删除付款合同
                        $(".btn-deletePaymentInfo").on('click', function () {
                            var contractPaymentId = $(this).attr('data-id');
                            var data = {
                                id: contractPaymentId,
                                projectId: id

                            };
                            confirm('确定要删除合同及合同下支付记录吗？', function () {
                                $.ajax({
                                    type: "POST",
                                    url: baseURL + "contract/contractreceipt/deleteContractPayment",
                                    headers: {'token': token},
                                    contentType: "application/json",
                                    data: JSON.stringify(data),
                                    success: function (r) {
                                        if (r.code == 0) {
                                            alert('操作成功', function (index) {
                                                layer.closeAll();
                                                var pWindow = window.parent;
                                                var oIframe = $('#main-content iframe', pWindow.document);
                                                oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                                            });
                                        } else {
                                            alert(r.msg);
                                        }
                                    }
                                });
                            });

                        });
                        //查看支付详情
                        $(".btn-getPaymentInfo").on('click', function () {
                            var contractPaymentId = $(this).attr('data-id');
                            console.log(contractPaymentId);
                            var updataprojectPaymentHTML = '<table id="jqGridPaymentInfo"></table>';
                            layer.open({
                                title: '支付详情',
                                type: 1,
                                skin: 'layui-layer-demo', //样式类名
                                closeBtn: 1, //显示关闭按钮
                                anim: 2,
                                area: ['520px', '400px'],
                                shadeClose: true, //开启遮罩关闭
                                content: updataprojectPaymentHTML
                            });
                            $("#jqGridPaymentInfo").jqGrid({
                                url: baseURL + 'contract/paymentinfo/list',
                                postData: {
                                    contractPaymentId: contractPaymentId
                                },
                                headers: {'token': token},
                                datatype: "json",
                                colModel: [
                                    {label: '支付金额', name: 'paymentMoney', width: 75, align: "center"},
                                    {label: '支付时间', name: 'paymentTimeStr', width: 75, align: "center"},
                                    {label: '本次支付占比', name: 'paymentProportion', width: 80, align: "center"},
                                    {
                                        label: '操作',
                                        name: 'createTime',
                                        index: "create_time",
                                        width: 90,
                                        formatter: function (value, options, row) {
                                            return '<a class="btn-deletePaymentProportionInfo" href="javascript:void(0);" data-id="' + row.id + '">' + '删除' + '</a>';
                                        }
                                    }
                                ],
                                viewrecords: true,
                                height: 300,
                                rowNum: 10,
                                rowList: [10, 30, 50],
                                rownumbers: true,
                                rownumWidth: 25,
                                autowidth: true,
                                multiselect: false,
                                pager: "#jqGridPagerPaymentInfo",
                                jsonReader: {
                                    root: "page.list",
                                    page: "page.currPage",
                                    total: "page.totalPage",
                                    records: "page.totalCount"
                                },
                                prmNames: {
                                    page: "page",
                                    rows: "limit",
                                    order: "order"
                                },
                                gridComplete: function () {
                                    //隐藏grid底部滚动条
                                    $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
                                    $(".btn-deletePaymentProportionInfo").on('click', function () {

                                        var paymentProportionInfoId = $(this).attr('data-id');
                                        console.log(paymentProportionInfoId)
                                        var data = {
                                            id: paymentProportionInfoId,
                                            projectId: id
                                        };

                                        confirm('确定要删除本次支付吗？', function () {
                                            $.ajax({
                                                type: "POST",
                                                url: baseURL + "contract/contractreceipt/deletePaymentProportionInfo",
                                                headers: {'token': token},
                                                contentType: "application/json",
                                                data: JSON.stringify(data),
                                                success: function (r) {
                                                    if (r.code == 0) {
                                                        alert('操作成功', function (index) {
                                                            layer.closeAll();
                                                            var pWindow = window.parent;
                                                            var oIframe = $('#main-content iframe', pWindow.document);
                                                            oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                                                        });
                                                    } else {
                                                        alert(r.msg);
                                                    }
                                                }
                                            });
                                        });
                                    });
                                }
                            });
                        });
                    },
                });
            jQuery("#" + subgrid_table_id).jqGrid('navGrid',
                "#" + pager_id, {
                    edit: false,
                    add: false,
                    del: false,
                    search: false
                });
        },
        subGridRowColapsed: function (subgrid_id, row_id) {
            // this function is called before removing the data
            //var subgrid_table_id;
            //subgrid_table_id = subgrid_id+"_t";
            //jQuery("#"+subgrid_table_id).remove();
        }
    });
    $("#listsg11").jqGrid('navGrid', '#pagersg11', {
        add: false,
        edit: false,
        del: false,
        search: false
    });
};

//渲染联系沟通单页面
function createContactSheet(id) {
    $("#jqGridContactSheet").jqGrid({
        url: baseURL + 'generator/contactsheet/list',
        postData: {
            'projectId': id,
            'token': token
        },
        datatype: "json",
        colModel: [
            {label: '联系单名称', name: 'sheetCompany', index: 'sheet_company'},
            {
                label: '联系单附件', name: 'sheetAccessory', formatter: function (value, options, row) {
                    console.log(row.accessoryUrl);
                    if (row.sheetAccessory) {
                        return '<a href= "' + row.accessoryUrl + '" target="_blank">' + row.sheetAccessory + '</a>';
                    } else {
                        return '';
                    }
                }
            },
            {
                label: '是否需要回复', name: 'sheetReply', formatter: function (value, options, row) {
                    //                             //console.log(row);
                    if (row.sheetReply == '1') {
                        return '<p><font color="red">是</font></p>';
                    } else if (row.sheetReply == '0') {
                        return '<p><font color="blue">否</font></p>';
                    }
                }
            },
            {
                label: '联系单回函', name: 'replyAccessory', formatter: function (value, options, row) {
                    console.log(row.replyAccessory);
                    if (row.sheetReply == '0') {
                        return '';
                    } else if (row.replyAccessory) {
                        return '<a href= "' + row.replyAccessoryUrl + '" target="_blank">' + row.replyAccessory + '</a>';
                    } else if (!row.replyAccessory && row.sheetReply == '1') {
                        return '<a class="btn-uploadReply" href="javascript:void(0);" data-id="' + row.accessoryId + '">' + '上传回复' + '</a>  ';
                    }
                }
            }
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: false,
        rownumWidth: 25,
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPagerContactSheet",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGridContactSheet").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            //上传联系沟通单回复
            $(".btn-uploadReply").on('click', function () {
                var replyAccessoryId = $(this).attr('data-id');
                var replyAccessoryHTML = '<div class="upload-box">' +
                    '<form class="file-loading" id="form1" method="post" enctype="multipart/form-data">' +
                    '<input id="file-replyAccessory" class="" type="file" name="file">' +
                    '</form>' +
                    '</div>';
                layer.open({
                    type: 1,
                    skin: 'layui-layer-demo', //样式类名
                    closeBtn: 1, //显示关闭按钮
                    anim: 2,
                    area: ['500px', '120px'],
                    shadeClose: true, //开启遮罩关闭
                    content: replyAccessoryHTML
                });
                $("#file-replyAccessory").fileinput({
                    // showUpload: false,
                    // showRemove: false,
                    uploadAsync: true,
                    showPreview: false,
                    language: 'zh',
                    textEncoding: "UTF-8",
                    uploadUrl: baseURL + "generator/contactsheet/uploadConferencesheet",
                    maxFileSize: 16300,
                    maxFileCount: 1,
                    enctype: 'multipart/form-data',
                    msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
                    dropZoneTitle: "请通过拖拽图片文件放到这里",
                    dropZoneClickTitle: "或者点击此区域添加图片",
                    uploadExtraData: function (previewId, index) {
                        var data = {
                            id: replyAccessoryId,
                            token: token,
                            creationUser: user.userId
                        };
                        return data;
                    },//这个是外带数据
                    // showBrowse: false,
                    browseOnZoneClick: true,
                    slugCallback: function (filename) {
                        return filename.replace('(', '_').replace(']', '_');
                    }
                });
                $('#file-replyAccessory').on("fileuploaded", function (event, data, previewId, index) {
                    var pWindow = window.parent;
                    var oIframe = $('#main-content iframe', pWindow.document);
                    oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 5);
                });
            });
        }
    });
};

$(function () {
    // 进入项目详情页加载loading
    var layerIndex = layer.load(1);
    //$('.select2').select2();
    var pWindow = window.parent;
    var sSrc = $('#main-content iframe', pWindow.document).attr('src');
    var token = window.localStorage.getItem("token");
    var id = getProjectId(sSrc).projectId;    // 项目id
    var sheetCompanyId = (new Date()).valueOf();
    var operateType = getProjectId(sSrc).operateType;
    $('#nav-p-progress li').eq(operateType).addClass('active').siblings().removeClass('active');
    $('#tab-p-content .tab-pane').eq(operateType).addClass('active').siblings().removeClass('active');
    if (operateType == 3) {
        createSummary(id);
    }
    ;
    if (operateType == 4) {
        createPayment(id);
    }
    ;
    if (operateType == 5) {
        createContactSheet(id);
    }
    ;
    // console.log(id);
    window.user = getUser();
    // 项目阶段切换
    $('#nav-p-graphic').on('click', '.graphic-rhombi', function () {
        // console.log($(this).index());
        // console.log($(this).index);
        $(this).closest('li').addClass('active-p').siblings('li').removeClass('active-p');
    });

    //项目信息
    $('#btn-details').on('click', function () {
        var role =0;
            // 时间控件
        $('#inp-date-start').datetimepicker({
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            todayHighlight: 1,
            showMeridian: 0,
            autoclose: 1,
            minView: 2
        });
        $.getJSON(baseURL + "generator/projectentity/queryInfo/" + id, {token: token}, function (r) {

            $.get(baseURL + 'generator/pojecttask/milepost/' + id, {token: token}, function (result) {
                var userId = user.userId;
                var roleIdList = user.roleIdList;
                var projectInfo = result.projectInfo;
                role = judgePm(userId, projectInfo.projectManagerId, roleIdList);   // 1：项目经理，2：任务负责人，3：主任
                if(role == 1||role == 3){
                    console.log(role)
                    //项目经理和admin允许修改
                    $("#projectNumber").attr("readonly",false);
                    $("#projectManager").attr("disabled",false);
                    $("#projectType").attr("disabled",false);
                    $("#applicantName").attr("disabled",false);
                    $("#line").attr("disabled",false);
                    $("#projectArea").attr("disabled",false);
                    $("#projectLevel").attr("disabled",false);
                    $("#corporateCheckingMoney").attr("disabled",false);
                    $("#inp-date-start").attr("disabled",false);
                    $("#projectName").attr("disabled",false);
                    $("#voltageType").attr("disabled",false);
                }else {
                    $("#projectNumber").attr("readonly",true);
                    $("#projectManager").attr("disabled",true);
                    $("#projectType").attr("disabled",true);
                    $("#applicantName").attr("disabled",true);
                    $("#line").attr("disabled",true);
                    $("#projectArea").attr("disabled",true);
                    $("#projectLevel").attr("disabled",true);
                    $("#corporateCheckingMoney").attr("disabled",true);
                    $("#inp-date-start").attr("disabled",true);
                    $("#projectName").attr("disabled",true);
                    $("#voltageType").attr("disabled",true);
                }
            });
            console.log("11111111111");
            console.log(r);
            //设置默认项目申请时间
            $("#inp-date-start").datetimepicker("setDate", StringToDate(r.projectEntity.projectTime));
            $('#projectName').val(r.projectEntity.projectName);
            $('#projectNumber').val(r.projectEntity.projectNumber);
            $('#applicantName').val(r.projectEntity.projectApplicant);
            if (r.projectEntity.relevantLinesName==null||r.projectEntity.relevantLinesName==""){
                $('#line').val(r.projectEntity.lineList);
            }else {
                $('#line').val(r.projectEntity.relevantLinesName);
            }
            var areaStr = r.projectEntity.projectArea || '';
            //$('#projectArea').text(getArea(areaStr));
            $("#projectArea").val(areaStr.split(',')).trigger('change')
            $('#projectType').val(r.projectEntity.projectType);
            $('#projectDescribe').val(r.projectEntity.projectDescribe);
            $('#voltageType').val(r.projectEntity.voltageType);
            $('#projectLevel').val(r.projectEntity.projectLevel);
            $('#projectManager').val(r.projectEntity.projectManagerId);
            $('#corporateCheckingMoney').val(r.projectEntity.corporateCheckingMoney);
            var aProjectType = $('#projectType option');
            for (var i = 0; i < aProjectType.length; i++) {
                if ($(aProjectType[i]).val() == r.projectEntity.projectType) {
                    $(aProjectType[i]).attr('selected', 'selected');
                }
            }
        });
    });
    //添加会议纪要
    $('#addConferenceSummary').on('click', function () {
        var pWindow = window.parent;
        pWindow.indexVm.main = 'modules/project/conferencesummary.html?projectId=' + id;
        pWindow.location.hash = 'modules/project/conferencesummary.html?projectId=' + id;
    });
    //导出合同及支付详情
    $('#exportReport').on('click', function () {
        console.log("导出");
        //导出投稿人的明细表
        window.location.href = baseURL + "contract/contractreceipt/export?projectId=" + id + "&token=" + token;
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth();
        if (month < 10) {
            month = '0' + month;
        }
        var dateFlag = year + month;
        console.log(dateFlag)
        /*var pWindow = window.parent;
        var oIframe = $('#main-content iframe', pWindow.document);
        oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);*/
    });
    //添加联系沟通单
    $('#addContactSheet').on('click', function () {
        var contactSheetHTML = '<form class="form-horizontal np-form" id="contactSheet-form">' +
            '<div class="form-group">' +
            '    <div class="col-sm-4 control-label">联系单位</div>' +
            '    <div class="col-sm-8">' +
            '        <input type="text" class="form-control" id="sheetCompany" placeholder="联系单位"/>' +
            '    </div>' +
            '</div>' +
            '<div class="form-group">' +
            '    <div class="col-sm-4 control-label">是否需要回复</div>' +
            '    <div class="col-sm-8">' +
            '        <select class="form-control" id="sheetReply">' +
            '            <option value="">' +
            '                请选择' +
            '            </option>' +
            '            <option value="1">' +
            '                是' +
            '            </option>' +
            '            <option value="0">' +
            '                否' +
            '            </option>' +
            '        </select>' +
            '    </div>' +
            '</div>' +
            '<div class="form-group">' +
            '    <div class="col-sm-4 control-label">上传附件</div>' +
            '<div class="col-sm-8">' +
            '    <div class="upload-box">' +
            '        <form class="file-loading" id="" method="post" enctype="multipart/form-data">' +
            '            <input id="file-sheetCompany" class="" type="file" name="file">' +
            '        </form>' +
            '    </div>' +
            '    </div>' +
            '</div>' +
            '</form>' +
            '<div class="form-group">' +
            ' <div class="col-sm-6 control-label"></div>' +
            '  <input type="button" class="btn btn-primary" id="saveContactSheet" value="提交"/>' +
            ' </div>';
        layer.open({
            type: 1,
            skin: 'layui-layer-demo', //样式类名
            closeBtn: 1, //显示关闭按钮
            anim: 2,
            area: ['600px', '300px'],
            shadeClose: true, //开启遮罩关闭
            content: contactSheetHTML
        });
        $("#file-sheetCompany").fileinput({
            showUpload: false,
            // showRemove: false,
            uploadAsync: true,
            showPreview: false,
            language: 'zh',
            textEncoding: "UTF-8",
            uploadUrl: baseURL + "generator/contactsheet/uploadConferencesheet",
            maxFileSize: 16300, /*设置允许图片大小单位KB*/
            maxFileCount: 1, /*允许最大上传数，可以多个，当前设置单个*/
            enctype: 'multipart/form-data',
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
            dropZoneTitle: "请通过拖拽图片文件放到这里",
            dropZoneClickTitle: "或者点击此区域添加图片",
            uploadExtraData: function (previewId, index) {
                var data = {
                    contactSheetId: sheetCompanyId,
                    token: token,
                    sheetAccessory: '1'
                };
                return data;
            },//这个是外带数据
            browseOnZoneClick: true,
            slugCallback: function (filename) {
                console.log(filename.replace('(', '_').replace(']', '_'));
                return filename.replace('(', '_').replace(']', '_');
            }
        });
        $('#saveContactSheet').on('click', function () {
            layer.closeAll('dialog');
            //在前端页面生成联系沟通单ID
            if (!$('#sheetCompany').val()) {
                alert("请填写联系单名称");
                return;
            }
            if (!$('#sheetReply').val()) {
                alert("请选择是否需要回复");
                return;
            }
            if ($('#file-sheetCompany').fileinput("getFilesCount") > 0) {
                //alert("123");
                $("#file-sheetCompany").fileinput("upload");
            }
            var sheetCompany = $('#sheetCompany').val();
            var sheetReply = $('#sheetReply').val();
            var data = {
                id: sheetCompanyId,
                sheetCompany: sheetCompany,
                sheetReply: sheetReply,
                projectId: id,
                creationUser: user.userId
            };
            console.log(data);
            $.ajax({
                type: "POST",
                url: baseURL + "generator/contactsheet/addConferencesheet",
                headers: {'token': token},
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (r) {
                    if (r.code == 0) {
                        alert('操作成功', function (index) {
                            layer.closeAll();
                            var pWindow = window.parent;
                            var oIframe = $('#main-content iframe', pWindow.document);
                            oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 5);
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        });
    });
    //添加收付款
    $('#addPayment').on('click', function () {
        var projectPaymentHTML = '<form class="form-horizontal np-form" id="projectPayment-form">' +
            '<div class="form-group">' +
            '    <div class="col-sm-4 control-label">类型</div>' +
            '    <div class="col-sm-8">' +
            '        <select class="form-control" id="paymentType">' +
            '            <option value="">' +
            '                请选择' +
            '            </option>' +
            '            <option value="1">' +
            '                付款' +
            '            </option>' +
            '            <option value="0">' +
            '                收款' +
            '            </option>' +
            '        </select>' +
            '    </div>' +
            '</div>' +
            '<div class="form-group">' +
            '    <div class="col-sm-4 control-label">时间</div>' +
            '    <div class="col-sm-8">' +
            '        <input type="text" ref="input1" class="form-control" id="inp-date-conferenceTime" placeholder="时间" name="conferenceTime">' +
            '    </div>' +
            '</div>' +
            '<div class="form-group">' +
            '    <div class="col-sm-4 control-label">金额</div>' +
            '<div class="col-sm-8">' +
            '    <input type="text" class="form-control" id="paymentAmount" placeholder="(单位:万)" oninput = "value=value.replace(/[^\\d]/g,\'\')"/>' +
            '    </div>' +
            '</div>' +
            '<div class="form-group">' +
            '    <div class="col-sm-4 control-label">备注</div>' +
            '<div class="col-sm-8">' +
            '    <input type="text" class="form-control" id="remark" placeholder="(备注)"/>' +
            '    </div>' +
            '</div>' +
            '</form>' +
            '<div class="form-group">' +
            ' <div class="col-sm-6 control-label"></div>' +
            '  <input type="button" class="btn btn-primary" id="saveProjectPayment" value="提交"/>' +
            ' </div>';
        layer.open({
            title: '新增收付款',
            type: 1,
            skin: 'layui-layer-demo', //样式类名
            closeBtn: 1, //显示关闭按钮
            anim: 2,
            area: ['630px', '330px'],
            shadeClose: true, //开启遮罩关闭
            content: projectPaymentHTML
        });
        // 时间控件
        $('#inp-date-conferenceTime').datetimepicker({
            minView: "month",
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            autoclose: true
        });
        $('#saveProjectPayment').on('click', function () {
            layer.closeAll('dialog');
            //在前端页面生成联系沟通单ID
            if (!$('#paymentType').val()) {
                alert("请选择收付款类型");
                return;
            }
            ;
            if (!$('#inp-date-conferenceTime').val()) {
                alert("请选择时间");
                return;
            }
            ;
            if (!$('#paymentAmount').val()) {
                alert("请填写金额");
                return;
            }
            ;
            //收款金额
            var receivablesSum = $('#receivablesSum').html();
            //付款金额
            var paymentSum = $('#paymentSum').html();
            //手动填写金额
            var paymentAmount = $('#paymentAmount').val();
            if ($('#paymentType').val() == '1' && paymentSum > receivablesSum) {
                confirm('付款金额已大于收款金额，确定需要继续进行付款操作吗？', function () {
                    var paymentType = $('#paymentType').val();
                    var paymentTime = $('#inp-date-conferenceTime').val();
                    var paymentAmount = $('#paymentAmount').val();
                    var remark = $('#remark').val();
                    var data = {
                        paymentType: paymentType,
                        paymentTime: paymentTime,
                        paymentAmount: paymentAmount,
                        remark: remark,
                        projectId: id,
                        creationUser: user.userId
                    };
                    console.log(data);
                    $.ajax({
                        type: "POST",
                        url: baseURL + "generator/projectpayment/save",
                        headers: {'token': token},
                        contentType: "application/json",
                        data: JSON.stringify(data),
                        success: function (r) {
                            if (r.code == 0) {
                                alert('操作成功', function (index) {
                                    layer.closeAll();
                                    var pWindow = window.parent;
                                    var oIframe = $('#main-content iframe', pWindow.document);
                                    oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                                });
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                });
            } else {
                var paymentType = $('#paymentType').val();
                var paymentTime = $('#inp-date-conferenceTime').val();
                var paymentAmount = $('#paymentAmount').val();
                var remark = $('#remark').val();
                var data = {
                    paymentType: paymentType,
                    paymentTime: paymentTime,
                    paymentAmount: paymentAmount,
                    remark: remark,
                    projectId: id,
                    creationUser: user.userId
                };
                console.log(data);
                $.ajax({
                    type: "POST",
                    url: baseURL + "generator/projectpayment/save",
                    headers: {'token': token},
                    contentType: "application/json",
                    data: JSON.stringify(data),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                layer.closeAll();
                                var pWindow = window.parent;
                                var oIframe = $('#main-content iframe', pWindow.document);
                                oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + id + '&operateType=' + 4);
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }
            ;
        });
    });

    // tab 切换
    $('#nav-p-progress').on('click', 'a', function () {
        // console.log($(this).parents('li').index());

        var _index = $(this).parents('li').index();
        $('#tab-p-content .tab-pane').eq(_index).addClass('active')
            .siblings().removeClass('active');

        if ($(this).hasClass('btn-summary')) {
            createSummary(id);
        } else if ($(this).hasClass('btn-communication')) {
            createContactSheet(id);
        } else if ($(this).hasClass('btn-payment')) {
            createPayment(id);
        }
    });

    $('#voltageType').on('change', function () {
        var voltageType = $('#voltageType').val();
        if (voltageType == 1) {
            console.log($("#projectType").find("option[value='2']"));
            $("#projectType").val('2');
        } else {
            $("#projectType").val('1');
            console.log($("#projectType").val())
        }
    });
    //修改项目信息
    /*$('#butSubmit').on('click', function () {
        var projectName = $('#projectName').val();
        var projectNumber = $('#projectNumber').val();
        var projectApplicant = $('#applicantName').val();
        var projectManager = $('#projectManager').val();
        var projectTime = $('#inp-date-start').val();
        var projectDescribe = $('#projectDescribe').val();
        var projectLevel = $('#projectLevel').val();
        var voltageType = $('#voltageType').val();
        var corporateCheckingMoney = $('#corporateCheckingMoney').val();
        var projectType = $('#projectType').val();
        var projectArea = $('#projectArea').val();
        var relevantLines = $('#line').val();

        var data = {
            projectName: projectName,
            projectNumber: projectNumber,
            projectApplicant: projectApplicant,
            projectManager: projectManager,
            projectTime: projectTime,
            projectDescribe: projectDescribe,
            projectLevel: projectLevel,
            voltageType: voltageType,
            token: token,
            corporateCheckingMoney: corporateCheckingMoney,
            projectType : projectType,
            projectArea : projectArea,
            relevantLinesName:relevantLines,
            id: id
        };
        console.log(data);
        $.ajax({
            type: "POST",
            headers: {
                token: "" + token
            },
            url: baseURL + "generator/projectentity/updateProject",
            contentType: "application/json",
            data: JSON.stringify(data),
            success: function (r) {
                if (r.code === 0) {
                    alert('操作成功', function (index) {
                    });
                } else {
                    alert(r.msg);
                }
            }
        });
    });*/
    window.operateEvents = {
        //设置责任人
        "click .btn-person": function (e, value, row, index) {
            var taskId = row.id;    // 任务Id
            var oBtn = $(this);
            $.ajax({
                type: 'POST',
                url: baseURL + 'sys/user/getUpPerson',
                success: function (result) {
                    console.log(result);
                    var deptList = result.userList;
                    var treeData = [];
                    for (var i = 0; i < deptList.length; i++) {
                        var temp = {
                            deptId: deptList[i].deptId,
                            text: deptList[i].deptName
                        };
                        var userList = deptList[i].userList;
                        if (userList.length > 0) {
                            var users = [];
                            for (var j = 0; j < userList.length; j++) {
                                var tempUser = {
                                    deptId: userList[j].deptId,
                                    id: userList[j].id,
                                    text: userList[j].userName
                                };
                                users.push(tempUser);
                            }
                            temp.nodes = users;
                        }
                        treeData.push(temp);
                    }
                    console.log(treeData);

                    var listHtml = '<div class="btn-pane">' +
                        '<button type="button" class="btn btn-primary" id="btn-ensure">确定</button>' +
                        '</div>' +
                        '<div class="data-pane">' +
                        '<div id="user-list"></div>' +
                        '</div>';

                    layer.open({
                        type: 1,
                        skin: 'layui-layer-demo', //样式类名
                        closeBtn: 1, //显示关闭按钮
                        anim: 2,
                        area: ['400px', '500px'],
                        shadeClose: true, //开启遮罩关闭
                        content: listHtml
                    });

                    $('#user-list').treeview({
                        levels: 1,
                        data: treeData
                    });

                    $('#btn-ensure').on('click', function () {
                        var user = $('#user-list').treeview('getSelected')[0];
                        console.log(user);
                        if (!user.id) {
                            return false;
                        } else {
                            var postData = {id: taskId, taskRespDept: user.deptId, taskRespUser: user.id};
                            $.ajax({
                                type: 'POST',
                                url: baseURL + 'generator/pojecttask/update',
                                contentType: "application/json",
                                data: JSON.stringify(postData),
                                success: function (result) {
                                    console.log(result);
                                    oBtn.text(user.text);
                                }
                            });
                            layer.close(layer.index);
                        }
                    });
                }
            })

        },
        //节点提交
        "click .btn-submit": function (e, value, row, index) {
            layer.confirm('确认提交 ' + row.name + ' 任务吗？', {
                btn: ['提交', '取消'] //按钮
            }, function () {
                layer.closeAll('dialog');
                $.get(baseURL + "generator/pojecttask/updataTaskSubmit/" + row.id, {token: token}, function (r) {
                    if (r.code == '0') {
                        alert('操作成功', function (index) {
                            var pWindow = window.parent;
                            var oIframe = $('#main-content iframe', pWindow.document);
                            oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + row.projectId);
                        });
                    } else {
                        alert(r.msg);
                    }
                    console.log(r);
                });
            }, function () {
                console.log('取消提交');
            });
        },
        //完工
        "click .btn-ensure": function (e, value, row, index) {
            layer.confirm('确认完工 ' + row.name + ' 任务吗？(确认完工，那么此任务便不可再编辑，但仍可查看任务下工作项附件)', {
                btn: ['完工', '取消'] //按钮
            }, function () {
                layer.closeAll('dialog');
                $.get(baseURL + "generator/pojecttask/updataTaskComplete/" + row.id + '/' + row.projectId + '/' + row.taskOrder, {token: token}, function (r) {
                    if (r.code == '0') {
                        alert('操作成功', function (index) {
                            var pWindow = window.parent;
                            var oIframe = $('#main-content iframe', pWindow.document);
                            oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + row.projectId);
                        });
                    } else {
                        alert(r.msg);
                    }
                    console.log(r);
                });
            }, function () {
                console.log('取消完工');
            });
        },
        //驳回
        "click .btn-reject": function (e, value, row, index) {
            console.log(user.userId)
            var str = "<div><p>驳回理由：<input type='text' id='price' /></p></div>";
            layer.confirm(str, {btn: ['确定', '取消'], title: "提示"}, function () {
                var price = $("#price").val();
                if (isBlank(price) || price == undefined) {
                    price = "1";
                }
                layer.confirm('确认驳回 ' + row.name + ' 任务吗？', {
                    btn: ['驳回', '取消'] //按钮
                }, function () {
                    layer.closeAll('dialog');
                    $.get(baseURL + "generator/pojecttask/updataTaskReject/" + row.id + "/" + price + "/" + user.userId, {token: token}, function (r) {
                        if (r.code == '0') {
                            alert('操作成功', function (index) {
                                var pWindow = window.parent;
                                var oIframe = $('#main-content iframe', pWindow.document);
                                oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + row.projectId);
                            });
                        } else {
                            alert(r.msg);
                        }
                    });
                }, function () {
                    console.log('取消驳回');
                });
            });
        },
        // 上传附件
        "click .btn-upload": function (e, value, row, index) {
            var workitemHTML =
                '<form　class="file-loading" id="form1" method="post"  enctype="multipart/form-data">' +
                '<input id="input-ficons-1" name="file" multiple type="file">' +
                '</form>';

            layer.open({
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                closeBtn: 1, //显示关闭按钮
                anim: 2,
                area: ['850px', '400px'],
                shadeClose: true, //开启遮罩关闭
                content: workitemHTML
            });
            $("#input-ficons-1").fileinput({
                language: 'zh',
                textEncoding: "UTF-8",
                showUpload: true,
                maxFileCount: 50,
                uploadUrl: baseURL + "generator/pojectworkitem/upload",
                uploadAsync: true,
                enctype: 'multipart/form-data',
                validateInitialCount: true,
                previewFileIcon: '<i class="fa fa-file"></i>',
                allowedPreviewTypes: null, // set to empty, null or false to disable preview for all types
                layoutTemplates: {
                    // actionDelete:'', //去除上传预览的缩略图中的删除图标
                    actionUpload: '',//去除上传预览缩略图中的上传图片；
                    actionZoom: ''   //去除上传预览缩略图中的查看详情预览的缩略图标。
                },
                previewFileIconSettings: {
                    'docx': '<i class="fa fa-file-word-o text-primary"></i>',
                    'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',
                    'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                    'jpg': '<i class="fa fa-file-photo-o text-warning"></i>',
                    'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>',
                    'zip': '<i class="fa fa-file-archive-o text-muted"></i>',
                },
                uploadExtraData: function (previewId, index) {
                    var data = {
                        workitemId: row.id,
                        projectId: row.projectId,
                        taskId: row.pid,
                        operationUser: user.userId,
                        //  operationMsg: $('#operation').val(),
                        token: token
                    };
                    return data;
                    console.log(data)
                },//这个是外带数据
                // showBrowse: false,
                browseOnZoneClick: true,
                slugCallback: function (filename) {
                    return filename.replace('(', '_').replace(']', '_');
                }
            });

            //上传文件成功，回调函数
            $('#input-ficons-1').on("fileuploaded", function (event, data, previewId, index) {
                var result = data.response; //后台返回的json
                $('#picid').val(result.id);//拿到后台传回来的id，给图片的id赋值序列化表单用
                $.ajax({//上传文件成功后再保存图片信息
                    url: baseURL + "generator/pojectworkitem/upload",
                    type: 'post',
                    dataType: 'json',
                    data: $('#form1').serialize(),//form表单的值
                    success: function (data, status) {
                        console.log(data);
                        if (status == 'success') {
                            layer.closeAll();
                            var pWindow = window.parent;
                            var oIframe = $('#main-content iframe', pWindow.document);
                            oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + row.projectId);
                        }
                    },
                    cache: false//不缓存
                });
            });
        },
        // 查看附件
        "click .btn-review": function (e, value, row, index) {
            $.get(baseURL + "generator/pojectoperation/query/" + row.id, {token: token}, function (data) {
                console.log(data);
                var workitemHTML = '<table id="operationTable">' +
                    '</table>';
                layer.open({
                    type: 1,
                    skin: 'layui-layer-demo', //样式类名
                    closeBtn: 1, //显示关闭按钮
                    anim: 2,
                    area: ['600px', '300px'],
                    shadeClose: true, //开启遮罩关闭
                    content: workitemHTML
                });
                var oTable = $('#operationTable');
                oTable.bootstrapTable({
                    data: data.pojectOperation,
                    striped: false,
                    //sidePagination: 'server',
                    checkboxHeader: true,
                    idField: 'id',
                    clickToSelect: true,
                    columns: [
                        {
                            field: 'operation',
                            title: '附件名称',
                            align: 'center',
                            events: 'operateEvents',
                            formatter: 'operateName'
                        },
                        {
                            field: 'operationDate',
                            title: '上传时间',
                            align: 'center'
                        },
                        {
                            field: 'operationUser',
                            align: 'center',
                            title: '上传人'
                        }
                    ]
                });

            });
        }
    };
    // 消息
    var vue = new Vue({
        el: '#message',
        data: {
            title: null,
            showList: true,
            projectMessage: [],
            currentMsg: ''
        },
        methods: {
            goDetails: function () {
                var str = $('#messContent').val(); //需要发送的内容
                if (str != null && str != "") {
                    var userId = user.userId;
                    var userName = user.name;
                    var data = {
                        messageContent: str,
                        sentUserId: userId,
                        sentUserName: userName,
                        projectId: id
                    };
                    console.log(data);
                    $.ajax({
                        type: "POST",
                        headers: {
                            token: "" + token
                        },
                        url: baseURL + "generator/prjectmessage/save",
                        contentType: "application/json",
                        data: JSON.stringify(data),
                        success: function (r) {
                            if (r.code === 0) {
                                alert('发送成功', function (index) {
                                });
                                var date = new Date().toLocaleDateString();
                                data.sentData = date;
                                vue.currentMsg = '';
                                vue.projectMessage.push(data);
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                }
            },
            getText: function () {
                $.get(baseURL + 'generator/prjectmessage/queryUserMessage/' + user.userId, function (result) {
                    console.log(result);
                });
            },
            getProjectMessage: function () {
                $.getJSON(baseURL + "generator/prjectmessage/queryProjectId/" + id, function (r) {
                    vue.projectMessage = r.prjectMessage;
                });
            },
            query: function () {
                vue.reload();
            }
        },
        mounted: function () {

        },
        created: function () {
            this.getProjectMessage();
        },
        reload: function (event) {
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                page: page
            }).trigger("reloadGrid");
        }
    });

    //项目规模
    var vm = new Vue({
        el: '#scale',
        data: {
            title: null,
            projectScale: {},
            showList: true,
            projectMessage: [],
            projectInfo: {},
            tableData:[],
        },
        methods: {
            getProjectScale: function () {
                $.getJSON(baseURL + "generator/projectscale/info/" + id, {token: token}, function (r) {
                    console.log(r);
                    vm.projectScale = r.projectScale;
                    if (vm.projectScale.managementConstructionAmount == 0) {
                        vm.projectScale.managementConstructionAmount = "";
                    }
                    if (vm.projectScale.tenderingAmount == 0) {
                        vm.projectScale.tenderingAmount = "";
                    }
                    if (vm.projectScale.engineeringSupervisionAmount == 0) {
                        vm.projectScale.engineeringSupervisionAmount = "";
                    }
                    if (vm.projectScale.surveyDesignAmount == 0) {
                        vm.projectScale.surveyDesignAmount = "";
                    }
                    if (vm.projectScale.otherAmount == 0) {
                        vm.projectScale.otherAmount = "";
                    }
                    if (vm.projectScale.firstPartyAmount == 0) {
                        vm.projectScale.firstPartyAmount = "";
                    }
                    if (vm.projectScale.threeProofingAmount == 0) {
                        vm.projectScale.threeProofingAmount = "";
                    }
                    if (vm.projectScale.civilConstructionAmount == 0) {
                        vm.projectScale.civilConstructionAmount = "";
                    }
                    if (vm.projectScale.electricalConstructionAmount == 0) {
                        vm.projectScale.electricalConstructionAmount = "";
                    }
                    if (vm.projectScale.prepareAmount == 0) {
                        vm.projectScale.prepareAmount = "";
                    }

                });
            },

            getProjectMessage: function () {
                $.getJSON(baseURL + "generator/prjectmessage/queryProjectId/" + id, {token: token}, function (r) {
                    // console.log(r);
                    vm.projectMessage = r.prjectMessage;
                    // console.log(vm.projectMessage);
                });
            },
            getinfo: function () {
                var oTable = $('#stage-table');
                $.get(baseURL + 'generator/pojecttask/milepost/' + id, {token: token}, function (result) {
                    var taskList = result.taskMap;
                    var userId = user.userId;
                    var roleIdList = user.roleIdList;
                    var projectInfo = result.projectInfo;
                    $('#projectInfoProjectName').text(projectInfo.projectName);
                    $('#projectInfoProjectNumber').text(projectInfo.projectNumber);
                    var role = judgePm(userId, projectInfo.projectManagerId, roleIdList);   // 1：项目经理，2：任务负责人
                    var tableData = []; // table 数据
                    var taskIds = {};   // 任务id数据
                    var taskLeaderIds = {}; // 任务负责人
                    for (var i = 0; i < taskList.length; i++) {
                        if (taskList[i].pid == 0) {
                            // 任务
                            taskIds[taskList[i].id] = 1;
                            taskLeaderIds[taskList[i].id] = taskList[i].dutyPersonId;
                        }
                    }
                    for (var i = 0; i < taskList.length; i++) {
                        var id = parseInt(taskList[i].id);
                        var pid = parseInt(taskList[i].pid);
                        if (pid == 0) {
                            if (role == 1 || role == 3) {
                                // 项目经理
                                if (taskList[i].status == 0) {
                                    // 已提交
                                    taskList[i].operation = ["submit:0", "ensure:1", "reject:1"];
                                } else if (taskList[i].status == 1 || taskList[i].status == 4) {
                                    // 已完成或未开始
                                    taskList[i].operation = [];
                                } else if (taskList[i].status == 2 || taskList[i].status == 3) {
                                    taskList[i].operation = ["submit:1", "ensure:0", "reject:0"];
                                }
                            } else if (role == 2) {
                                // 任务负责人
                                // 0:提交，1:完成，2:驳回，3:进行中，4:未开始
                                // 0 1 4
                                if (userId == taskList[i].dutyPersonId) {
                                    if (taskList[i].status == 2 || taskList[i].status == 3) {
                                        // 进行中，驳回
                                        taskList[i].operation = ["submit:1"];
                                    } else {
                                        taskList[i].operation = ["submit:0"];
                                    }
                                } else {
                                    taskList[i].operation = [];
                                }
                            }
                        } else {
                            // 工作项
                            if (role == 1 || role == 3) {
                                // 项目经理
                                taskList[i].operation = ["upload:1", "review:1"];
                            } else if (role == 2) {
                                // 任务负责人
                                if (userId == taskLeaderIds[taskList[i].pid]) {
                                    // 负责人负责的任务下的工作项
                                    taskList[i].operation = ["upload:1", "review:1"];
                                } else {
                                    // 其他任务下的工作项
                                    taskList[i].operation = ["review:1"];
                                }
                            }
                        }
                        taskList[i].id = id;
                        taskList[i].pid = pid;
                        tableData.push(taskList[i]);
                    }
                    console.log(tableData);
                    oTable.bootstrapTable({
                        data: tableData,
                        striped: false,
                        //sidePagination: 'server',
                        idField: 'id',
                        columns: [
                            {
                                field: 'ck',
                                checkbox: true
                            },
                            {
                                field: 'name',
                                title: '项目名称'
                            },
                            {
                                field: 'status',
                                title: '状态',
                                align: 'center',
                                formatter: 'statusFormatter'
                            },
                            {
                                field: 'startTime',
                                align: 'center',
                                title: '开始时间',
                                formatter: 'dateFormatter',
                                formatter: function (value, row, index) {''
                                    if (value&&(role == 1 || role == 3)){
                                        return '<input readonly="readonly" data-startIndex="'+index+'" class="btn btn-xs btn-default btn-person updata-time" value="'+value+'" id="startTime'+index+'">'
                                    }else {
                                        return value;
                                    }
                                }
                            },
                            {
                                field: 'endTime',
                                align: 'center',
                                title: '结束时间',
                                formatter: 'dateFormatter',
                                formatter: function (value, row, index) {''
                                    if (value&&(role == 1 || role == 3)){
                                        return '<input readonly="readonly" data-endIndex="'+index+'" class="btn btn-xs btn-default btn-person updata-time" value="'+value+'" id="endTime'+index+'">'
                                    }else {
                                        return value;
                                    }
                                }
                            },
                            {
                                field: 'dutyPerson',
                                title: '责任人',
                                align: 'center',
                                events: 'operateEvents',
                                formatter: function (value, row, index) {
                                    if (role == 1 || role == 3) {
                                        if (value == '1') {
                                            return '<a class="btn btn-xs btn-default btn-person">未设置</a>';
                                        } else if (value == '') {
                                            return '<span></span>';
                                        } else {
                                            return '<a class="btn btn-xs btn-default btn-person">' + value + '</a>';
                                        }
                                    } else {
                                        if (value == '1') {
                                            return '<a class="btn btn-xs btn-default btn-person">未设置</a>';
                                        } else if (value == '') {
                                            return '<span></span>';
                                        } else {
                                            return '<span class="">' + value + '</span>';
                                        }
                                    }
                                }
                            },
                            {
                                field: 'operation',
                                title: '操作',
                                align: 'center',
                                events: 'operateEvents',
                                formatter: 'operateFormatter'
                            }
                        ],
                        treeShowField: 'name',
                        parentIdField: 'pid',
                        onPostBody:function () {//table渲染完成后初始化日期控件
                            $('.updata-time').datetimepicker({
                                language:'zh-CN',
                                format: 'yyyy-mm-dd',
                                todayHighlight:1,
                                showMeridian: 0,
                                autoclose: 1,
                                minView: 2
                            }).on('changeDate',function(ev){
                                var data = oTable.bootstrapTable('getData',false);
                                //修改日期后触发
                                if($(this).attr('data-startIndex')){
                                    //开始时间
                                    var index = parseInt($(this).attr('data-startIndex'));
                                    if(index==0){
                                        //第一条任务
                                        var date1 = new Date(data[index].endTime);
                                        var date2 = new Date($(this).val());
                                        if((date1>date2) || (""==data[index].endTime)){
                                            //结束时间大于开始时间
                                            oTable.bootstrapTable('updateCell', {
                                                index: index,
                                                field: 'startTime',
                                                value: $(this).val()
                                            });
                                            $.ajax({
                                                url: baseURL + "generator/pojecttask/update",
                                                type: 'post',
                                                dataType: 'json',
                                                contentType: "application/json",
                                                data: JSON.stringify({id:data[index].id,taskFactStartDate:$(this).val()}),
                                                success: function (e) {
                                                    if(e.code==0){
                                                    }else {
                                                        //还原时间
                                                        alert('修改失败');
                                                        oTable.bootstrapTable('load', data);
                                                    }
                                                },
                                            });
                                        }else {
                                            //还原时间
                                            alert('结束时间不能小于开始时间');
                                            oTable.bootstrapTable('load', data);
                                            // oTable.bootstrapTable('refresh');
                                            //oTable.bootstrapTable('refreshOptions');
                                            //$(this).val(data[index].startTime);
                                        }
                                    }else {
                                        //非第一条任务
                                        var date1 = new Date(data[index-1].startTime);//上一个任务开始时间
                                        var date2 = new Date($(this).val());
                                        var date3 = new Date(data[index].endTime);//当前任务结束时间
                                        if((date1<=date2&&date2<=date3) || (date1<=date2&&""==data[index].endTime)){
                                            oTable.bootstrapTable('updateCell', {
                                                index: index,
                                                field: 'startTime',
                                                value: $(this).val()
                                            });
                                            $.ajax({
                                                url: baseURL + "generator/pojecttask/update",
                                                type: 'post',
                                                dataType: 'json',
                                                contentType: "application/json",
                                                data: JSON.stringify({id:data[index].id,taskFactStartDate:$(this).val()}),
                                                success: function (e) {
                                                    if(e.code==0){
                                                    }else {
                                                        //还原时间
                                                        alert('修改失败');
                                                        oTable.bootstrapTable('load', data);
                                                    }
                                                },
                                            });
                                            oTable.bootstrapTable('updateCell', {
                                                index: index-1,
                                                field: 'endTime',
                                                value: $(this).val()
                                            });
                                            $.ajax({
                                                url: baseURL + "generator/pojecttask/update",
                                                type: 'post',
                                                dataType: 'json',
                                                contentType: "application/json",
                                                data: JSON.stringify({id:data[index-1].id,taskFactEndDate:$(this).val()}),
                                                success: function (e) {
                                                    if(e.code==0){
                                                    }else {
                                                        //还原时间
                                                        alert('修改失败');
                                                        oTable.bootstrapTable('load', data);
                                                    }
                                                },
                                            });
                                        }else if (date1>date2){
                                            //还原时间
                                            alert('开始时间不能小于上个任务开始时间');
                                            oTable.bootstrapTable('load', data);
                                        }else if(date2>date3){
                                            //还原时间
                                            alert('结束时间不能小于开始时间');
                                            oTable.bootstrapTable('load', data);
                                        }else {
                                            oTable.bootstrapTable('load', data);
                                        }
                                    }

                                }else if($(this).attr('data-endIndex')){
                                    //结束时间时间
                                    var index = parseInt($(this).attr('data-endIndex'));
                                    if(data[index+1].pid ==0){
                                        //不是最后一条任务
                                        var date1 = new Date(data[index+1].endTime);//下一个任务结束时间
                                        var date2 = new Date($(this).val());
                                        var date3 = new Date(data[index].startTime);//当前任务开始时间
                                        if((date1>=date2&&date2>=date3) || (date2>=date3&&""==data[index+1].endTime)){
                                            //下一个任务的结束时间大于当前结束时间
                                            oTable.bootstrapTable('updateCell', {
                                                index: index,
                                                field: 'endTime',
                                                value: $(this).val()
                                            });
                                            $.ajax({
                                                url: baseURL + "generator/pojecttask/update",
                                                type: 'post',
                                                dataType: 'json',
                                                contentType: "application/json",
                                                data: JSON.stringify({id:data[index].id,taskFactEndDate:$(this).val()}),
                                                success: function (e) {
                                                    if(e.code==0){
                                                    }else {
                                                        //还原时间
                                                        alert('修改失败');
                                                        oTable.bootstrapTable('load', data);
                                                    }
                                                },
                                            });
                                            oTable.bootstrapTable('updateCell', {
                                                index: index+1,
                                                field: 'startTime',
                                                value: $(this).val()
                                            });
                                            $.ajax({
                                                url: baseURL + "generator/pojecttask/update",
                                                type: 'post',
                                                dataType: 'json',
                                                contentType: "application/json",
                                                data: JSON.stringify({id:data[index+1].id,taskFactStartDate:$(this).val()}),
                                                success: function (e) {
                                                    if(e.code==0){
                                                    }else {
                                                        //还原时间
                                                        alert('修改失败');
                                                        oTable.bootstrapTable('load', data);
                                                    }
                                                },
                                            });
                                        }else if(date2>date1){
                                            //还原时间
                                            alert('结束时间不能大于下个任务结束时间');
                                            oTable.bootstrapTable('load', data);
                                        }else if(date2<date3){
                                            //还原时间
                                            alert('结束时间不能小于开始时间');
                                            oTable.bootstrapTable('load', data);
                                        }else {
                                            oTable.bootstrapTable('load', data);
                                        }
                                    }else {
                                        //最后一条任务
                                        var date2 = new Date($(this).val());
                                        var date3 = new Date(data[index].startTime);
                                        if(date2>date3){
                                            //下一个任务的结束时间大于当前结束时间
                                            oTable.bootstrapTable('updateCell', {
                                                index: index,
                                                field: 'endTime',
                                                value: $(this).val()
                                            });
                                            $.ajax({
                                                url: baseURL + "generator/pojecttask/update",
                                                type: 'post',
                                                dataType: 'json',
                                                contentType: "application/json",
                                                data: JSON.stringify({id:data[index].id,taskFactEndDate:$(this).val()}),
                                                success: function (e) {
                                                    if(e.code==0){
                                                    }else {
                                                        //还原时间
                                                        alert('修改失败');
                                                        oTable.bootstrapTable('load', data);
                                                    }
                                                },
                                            });
                                        }else if(date2<date3){
                                            //还原时间
                                            alert('结束时间不能小于开始时间');
                                            oTable.bootstrapTable('load', data);
                                            //oTable.bootstrapTable('refreshOptions');
                                            //$(this).val(data[index].endTime);
                                        }else {
                                            oTable.bootstrapTable('load', data);
                                        }
                                    }

                                }

                            });
                        },
                        onResetView: function (data) {
                            oTable.treegrid({
                                initialState: 'collapsed',// 所有节点都折叠
                                // initialState: 'expanded',// 所有节点都展开，默认展开
                                treeColumn: 1,
                                expanderExpandedClass: 'glyphicon glyphicon-minus',  //图标样式
                                expanderCollapsedClass: 'glyphicon glyphicon-plus',
                                onChange: function () {
                                    oTable.bootstrapTable('resetWidth');
                                }
                            });
                            //只展开树形的第一级节点
                            oTable.treegrid('getRootNodes').treegrid('expand');
                        }
                    });

                    // 关闭页面加载时的loading
                    layer.close(layerIndex);
                });
            },
            saveOrScale: function (event) {
                vm.projectScale.scalePlannMoney = $("#scalePlannMoney").text();
                vm.projectScale.creationUser = user.userId;
                console.log(vm.projectScale.creationUser);
                vm.projectScale.projectId = id;
                if (!vm.projectScale.scalePlannMoney || vm.projectScale.scalePlannMoney == 0) {
                    alert(" 请输入金额！");
                    return false;
                }
                $.ajax({
                    async: false,
                    type: "POST",
                    url: baseURL + "generator/projectscale/updateOrSave",
                    contentType: "application/json",
                    data: JSON.stringify(vm.projectScale),
                    success: function (r) {
                        if (r.code == 0) {
                            alert("操作成功");
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            },
            query: function () {
                vm.reload();
            },
            getInfo: function (id) {
                $.get(baseURL + "generator/projectscale/info/" + id, {token: token}, function (r) {
                    console.log(r);
                    vm.projectScale = r.projectScale;
                });
            }
        },
        mounted: function () {

        },
        created: function () {
            this.getinfo();
            this.getProjectScale();
            this.getProjectMessage();
        },
        reload: function (event) {
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                page: page
            }).trigger("reloadGrid");
        }
    });

    //项目信息
    var det = new Vue({
        el: '#details',
        data: {
            projectEntity: {
            },
            pmList: [], // 项目经理列表
            applicantList: [], // 项目申请方列表
            areaList:[]
        },
        methods: {
            butSubmit: function () {
                var projectName = $('#projectName').val();
                var projectNumber = $('#projectNumber').val();
                var projectApplicant = $('#applicantName').val();
                var projectManager = $('#projectManager').val();
                var projectTime = $('#inp-date-start').val();
                var projectDescribe = $('#projectDescribe').val();
                var projectLevel = $('#projectLevel').val();
                var voltageType = $('#voltageType').val();
                var corporateCheckingMoney = $('#corporateCheckingMoney').val();
                var projectType = $('#projectType').val();
                var projectAreas = $('#projectArea').val();
                var relevantLines = $('#line').val();

                var projectArea = '';
                if (projectAreas!= null && projectAreas.length != 0){
                    projectArea = projectAreas.join(',');
                };
                var data = {
                    projectName: projectName,
                    projectNumber: projectNumber,
                    projectApplicant: projectApplicant,
                    projectManager: projectManager,
                    projectTime: projectTime,
                    projectDescribe: projectDescribe,
                    projectLevel: projectLevel,
                    voltageType: voltageType,
                    token: token,
                    corporateCheckingMoney: corporateCheckingMoney,
                    projectType : projectType,
                    projectArea : projectArea,
                    relevantLinesName:relevantLines,
                    id: id
                };
                console.log(data);
                $.ajax({
                    type: "POST",
                    headers: {
                        token: "" + token
                    },
                    url: baseURL + "generator/projectentity/updateProject",
                    contentType: "application/json",
                    data: JSON.stringify(data),
                    success: function (r) {
                        if (r.code === 0) {
                            alert('操作成功', function (index) {
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }
        },
        mounted: function () {
            var _this = this;
            $.get(baseURL+'sys/user/listpm', function (result) {
                console.log(result);
                var list = result.pmList;
                var tempList = [];
                for (var i = 0; i < list.length; i++) {
                    var temp = {
                        pmName: list[i].name,
                        pmId: list[i].userId
                    };
                    tempList.push(temp);
                }
                _this.pmList = tempList;
            });

            $.get(baseURL+'generator/projectapplicantinfo/alllist', function (result) {
                console.log(result);
                //项目申请方
                _this.applicantList = result.applicantList;
            });

            _this.areaList = [
                {
                    id: 10001,
                    text: '武昌区'
                },
                {
                    id: 10002,
                    text: '汉口区'
                },
                {
                    id: 10003,
                    text: '汉阳区'
                },
                {
                    id: 10004,
                    text: '东新区'
                },
                {
                    id: 10005,
                    text: '沌口区'
                },
                {
                    id: 10006,
                    text: '东西湖区'
                },
                {
                    id: 10007,
                    text: '黄陂区'
                },
                {
                    id: 10008,
                    text: '新洲区'
                },
                {
                    id: 10009,
                    text: '汉南区'
                },
                {
                    id: 10010,
                    text: '江夏区'
                },
                {
                    id: 10011,
                    text: '蔡甸区'
                }
            ];

            //项目所属区域
            $('#projectArea').select2({
                data: _this.areaList,
                placeholder:'请选择项目所属区域',//默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,//允许清空
                multiple: true
                /* multiple: false, //启用多选
                 maximumSelectionSize:1*/
            });
        },
        created: function () {
        },
        reload: function (event) {
        }
    });

});

function updataTime(id) {
    console.log(id);
}
